hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
f759dcd972aa30208a673664b0b4b384f1a7047a
1,362
ex
Elixir
lib/mix/k8s/swagger.ex
coryodaniel/k8s_client
88fb9490db72e947b2d216637769134bc4ebdfbd
[ "MIT" ]
5
2019-01-12T16:56:05.000Z
2021-04-10T04:06:13.000Z
lib/mix/k8s/swagger.ex
coryodaniel/k8s_client
88fb9490db72e947b2d216637769134bc4ebdfbd
[ "MIT" ]
12
2019-01-08T23:42:56.000Z
2019-01-26T19:07:50.000Z
lib/mix/k8s/swagger.ex
coryodaniel/k8s_client
88fb9490db72e947b2d216637769134bc4ebdfbd
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.K8s.Swagger do @moduledoc """ Download a kubernetes swagger spec. """ use Mix.Task @switches [version: :string] @aliases [v: :version] @defaults [version: "master"] @shortdoc "Downloads a k8s swagger spec" @spec run([binary()]) :: nil | :ok def run(args) do {:ok, _started} = Application.ensure_all_started(:httpoison) {opts, _, _} = Mix.K8s.parse_args(args, @defaults, switches: @switches, aliases: @aliases) url = url(opts[:version]) version = opts[:version] target = "./priv/swagger/#{version}.json" with {:ok, response} <- HTTPoison.get(url) do Mix.Generator.create_file(target, response.body) else {:error, msg} -> raise_with_help(msg) end end def url(version) do case version do "master" -> "https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json" version -> "https://raw.githubusercontent.com/kubernetes/kubernetes/release-#{version}/api/openapi-spec/swagger.json" end end @spec raise_with_help(binary) :: none() def raise_with_help(msg) do Mix.raise(""" #{msg} mix k8s.swagger downloads a K8s swagger file to priv/swagger/ Downloading master: mix k8s.swagger Downloading a specific version: mix k8s.swagger --version 1.13 """) end end
25.222222
114
0.654919
f759e203b6aad5a1df48ced28ceb2c1c9a04f1d0
66,083
ex
Elixir
lib/elixir/lib/enum.ex
Gazler/elixir
e934e3c92edbc9c83da7795ec3a028ff86218c4b
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
Gazler/elixir
e934e3c92edbc9c83da7795ec3a028ff86218c4b
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
Gazler/elixir
e934e3c92edbc9c83da7795ec3a028ff86218c4b
[ "Apache-2.0" ]
null
null
null
defprotocol Enumerable do @moduledoc """ Enumerable protocol used by `Enum` and `Stream` modules. When you invoke a function in the `Enum` module, the first argument is usually a collection that must implement this protocol. For example, the expression Enum.map([1, 2, 3], &(&1 * 2)) invokes underneath `Enumerable.reduce/3` to perform the reducing operation that builds a mapped list by calling the mapping function `&(&1 * 2)` on every element in the collection and cons'ing the element with an accumulated list. Internally, `Enum.map/2` is implemented as follows: def map(enum, fun) do reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse() end Notice the user given function is wrapped into a `reducer` function. The `reducer` function must return a tagged tuple after each step, as described in the `acc/0` type. The reason the accumulator requires a tagged tuple is to allow the reducer function to communicate to the underlying enumerable the end of enumeration, allowing any open resource to be properly closed. It also allows suspension of the enumeration, which is useful when interleaving between many enumerables is required (as in zip). Finally, `Enumerable.reduce/3` will return another tagged tuple, as represented by the `result/0` type. """ @typedoc """ The accumulator value for each step. It must be a tagged tuple with one of the following "tags": * `:cont` - the enumeration should continue * `:halt` - the enumeration should halt immediately * `:suspend` - the enumeration should be suspended immediately Depending on the accumulator value, the result returned by `Enumerable.reduce/3` will change. Please check the `result` type docs for more information. In case a reducer function returns a `:suspend` accumulator, it must be explicitly handled by the caller and never leak. """ @type acc :: {:cont, term} | {:halt, term} | {:suspend, term} @typedoc """ The reducer function. Should be called with the collection element and the accumulator contents. Returns the accumulator for the next enumeration step. """ @type reducer :: (term, term -> acc) @typedoc """ The result of the reduce operation. It may be *done* when the enumeration is finished by reaching its end, or *halted*/*suspended* when the enumeration was halted or suspended by the reducer function. In case a reducer function returns the `:suspend` accumulator, the `:suspended` tuple must be explicitly handled by the caller and never leak. In practice, this means regular enumeration functions just need to be concerned about `:done` and `:halted` results. Furthermore, a `:suspend` call must always be followed by another call, eventually halting or continuing until the end. """ @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation} @typedoc """ A partially applied reduce function. The continuation is the closure returned as a result when the enumeration is suspended. When invoked, it expects a new accumulator and it returns the result. A continuation is easily implemented as long as the reduce function is defined in a tail recursive fashion. If the function is tail recursive, all the state is passed as arguments, so the continuation would simply be the reducing function partially applied. """ @type continuation :: (acc -> result) @doc """ Reduces the collection into a value. Most of the operations in `Enum` are implemented in terms of reduce. This function should apply the given `reducer` function to each item in the collection and proceed as expected by the returned accumulator. As an example, here is the implementation of `reduce` for lists: def reduce(_, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun) """ @spec reduce(t, acc, reducer) :: result def reduce(collection, acc, fun) @doc """ Checks if a value exists within the collection. It should return `{:ok, boolean}`. If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and the match (`===`) operator is used. This algorithm runs in linear time. Please force use of the default algorithm unless you can implement an algorithm that is significantly faster. """ @spec member?(t, term) :: {:ok, boolean} | {:error, module} def member?(collection, value) @doc """ Retrieves the collection's size. It should return `{:ok, size}`. If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and the match (`===`) operator is used. This algorithm runs in linear time. Please force use of the default algorithm unless you can implement an algorithm that is significantly faster. """ @spec count(t) :: {:ok, non_neg_integer} | {:error, module} def count(collection) end defmodule Enum do import Kernel, except: [max: 2, min: 2] @moduledoc """ Provides a set of algorithms that enumerate over collections according to the `Enumerable` protocol: iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end) [2, 4, 6] Some particular types, like dictionaries, yield a specific format on enumeration. For dicts, the argument is always a `{key, value}` tuple: iex> dict = %{a: 1, b: 2} iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end) [a: 2, b: 4] Note that the functions in the `Enum` module are eager: they always start the enumeration of the given collection. The `Stream` module allows lazy enumeration of collections and provides infinite streams. Since the majority of the functions in `Enum` enumerate the whole collection and return a list as result, infinite streams need to be carefully used with such functions, as they can potentially run forever. For example: Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1) """ @compile :inline_list_funcs @type t :: Enumerable.t @type element :: any @type index :: non_neg_integer @type default :: any # Require Stream.Reducers and its callbacks require Stream.Reducers, as: R defmacrop skip(acc) do acc end defmacrop next(_, entry, acc) do quote do: [unquote(entry)|unquote(acc)] end defmacrop acc(h, n, _) do quote do: {unquote(h), unquote(n)} end defmacrop next_with_acc(f, entry, h, n, _) do quote do {[unquote(entry)|unquote(h)], unquote(n)} end end @doc """ Invokes the given `fun` for each item in the `collection` and returns `false` if at least one invocation returns `false` or `nil`. Otherwise returns `true`. ## Examples iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end) true iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end) false If no function is given, it defaults to checking if all items in the collection are truthy values. iex> Enum.all?([1, 2, 3]) true iex> Enum.all?([1, nil, 3]) false """ @spec all?(t) :: boolean @spec all?(t, (element -> as_boolean(term))) :: boolean def all?(collection, fun \\ fn(x) -> x end) def all?(collection, fun) when is_list(collection) do do_all?(collection, fun) end def all?(collection, fun) do Enumerable.reduce(collection, {:cont, true}, fn(entry, _) -> if fun.(entry), do: {:cont, true}, else: {:halt, false} end) |> elem(1) end @doc """ Invokes the given `fun` for each item in the `collection` and returns `true` if at least one invocation returns a truthy value. Returns `false` otherwise. ## Examples iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) false iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) true If no function is given, it defaults to checking if at least one item in the collection is a truthy value. iex> Enum.any?([false, false, false]) false iex> Enum.any?([false, true, false]) true """ @spec any?(t) :: boolean @spec any?(t, (element -> as_boolean(term))) :: boolean def any?(collection, fun \\ fn(x) -> x end) def any?(collection, fun) when is_list(collection) do do_any?(collection, fun) end def any?(collection, fun) do Enumerable.reduce(collection, {:cont, false}, fn(entry, _) -> if fun.(entry), do: {:halt, true}, else: {:cont, false} end) |> elem(1) end @doc """ Finds the element at the given index (zero-based). Returns `default` if index is out of bounds. Note this operation takes linear time. In order to access the element at index `n`, it will need to traverse `n` previous elements. ## Examples iex> Enum.at([2, 4, 6], 0) 2 iex> Enum.at([2, 4, 6], 2) 6 iex> Enum.at([2, 4, 6], 4) nil iex> Enum.at([2, 4, 6], 4, :none) :none """ @spec at(t, integer, default) :: element | default def at(collection, n, default \\ nil) do case fetch(collection, n) do {:ok, h} -> h :error -> default end end @doc """ Shortcut to `chunk(collection, n, n)`. """ @spec chunk(t, non_neg_integer) :: [list] def chunk(collection, n), do: chunk(collection, n, n, nil) @doc """ Returns a collection of lists containing `n` items each, where each new chunk starts `step` elements into the collection. `step` is optional and, if not passed, defaults to `n`, i.e. chunks do not overlap. If the final chunk does not have `n` elements to fill the chunk, elements are taken as necessary from `pad` if it was passed. If `pad` is passed and does not have enough elements to fill the chunk, then the chunk is returned anyway with less than `n` elements. If `pad` is not passed at all or is `nil`, then the partial chunk is discarded from the result. ## Examples iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2) [[1, 2], [3, 4], [5, 6]] iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2) [[1, 2, 3], [3, 4, 5]] iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7]) [[1, 2, 3], [3, 4, 5], [5, 6, 7]] iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, []) [[1, 2, 3], [4, 5, 6]] """ @spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list] def chunk(collection, n, step, pad \\ nil) when n > 0 and step > 0 do limit = :erlang.max(n, step) {acc, {buffer, i}} = reduce(collection, {[], {[], 0}}, R.chunk(n, step, limit)) if is_nil(pad) || i == 0 do :lists.reverse(acc) else buffer = :lists.reverse(buffer, take(pad, n - i)) :lists.reverse([buffer|acc]) end end @doc """ Splits `collection` on every element for which `fun` returns a new value. ## Examples iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1)) [[1], [2, 2], [3], [4, 4, 6], [7, 7]] """ @spec chunk_by(t, (element -> any)) :: [list] def chunk_by(collection, fun) do {acc, res} = reduce(collection, {[], nil}, R.chunk_by(fun)) case res do {buffer, _} -> :lists.reverse([:lists.reverse(buffer) | acc]) nil -> [] end end @doc """ Given an enumerable of enumerables, concatenates the enumerables into a single list. ## Examples iex> Enum.concat([1..3, 4..6, 7..9]) [1, 2, 3, 4, 5, 6, 7, 8, 9] iex> Enum.concat([[1, [2], 3], [4], [5, 6]]) [1, [2], 3, 4, 5, 6] """ @spec concat(t) :: t def concat(enumerables) do do_concat(enumerables) end @doc """ Concatenates the enumerable on the right with the enumerable on the left. This function produces the same result as the `Kernel.++/2` operator for lists. ## Examples iex> Enum.concat(1..3, 4..6) [1, 2, 3, 4, 5, 6] iex> Enum.concat([1, 2, 3], [4, 5, 6]) [1, 2, 3, 4, 5, 6] """ @spec concat(t, t) :: t def concat(left, right) when is_list(left) and is_list(right) do left ++ right end def concat(left, right) do do_concat([left, right]) end defp do_concat(enumerable) do fun = &[&1|&2] reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse end @doc """ Returns the collection's size. ## Examples iex> Enum.count([1, 2, 3]) 3 """ @spec count(t) :: non_neg_integer def count(collection) when is_list(collection) do :erlang.length(collection) end def count(collection) do case Enumerable.count(collection) do {:ok, value} when is_integer(value) -> value {:error, module} -> module.reduce(collection, {:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1) end end @doc """ Returns the count of items in the collection for which `fun` returns a truthy value. ## Examples iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end) 2 """ @spec count(t, (element -> as_boolean(term))) :: non_neg_integer def count(collection, fun) do Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) -> {:cont, if(fun.(entry), do: acc + 1, else: acc)} end) |> elem(1) end @doc """ Enumerates the collection, returning a list where all consecutive duplicated elements are collapsed to a single element. Elements are compared using `===`. ## Examples iex> Enum.dedup([1, 2, 3, 3, 2, 1]) [1, 2, 3, 2, 1] """ @spec dedup(t) :: list def dedup(collection) do dedup_by(collection, fn x -> x end) end @doc """ Enumerates the collection, returning a list where all consecutive duplicated elements are collapsed to a single element. The function `fun` maps every element to a term which is used to determine if two elements are duplicates. ## Examples iex> Enum.dedup_by([{1, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end) [{1, :x}, {2, :y}, {1, :x}] iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end) [5, 1, 3, 2] """ @spec dedup_by(t, (element -> term)) :: list def dedup_by(collection, fun) when is_function(fun, 1) do {list, _} = reduce(collection, {[], []}, R.dedup(fun)) :lists.reverse(list) end @doc """ Drops the first `count` items from `collection`. If a negative value `count` is given, the last `count` values will be dropped. The collection is enumerated once to retrieve the proper index and the remaining calculation is performed from the end. ## Examples iex> Enum.drop([1, 2, 3], 2) [3] iex> Enum.drop([1, 2, 3], 10) [] iex> Enum.drop([1, 2, 3], 0) [1, 2, 3] iex> Enum.drop([1, 2, 3], -1) [1, 2] """ @spec drop(t, integer) :: list def drop(collection, count) when is_list(collection) and count >= 0 do do_drop(collection, count) end def drop(collection, count) when count >= 0 do res = reduce(collection, count, fn x, acc when is_list(acc) -> [x|acc] x, 0 -> [x] _, acc when acc > 0 -> acc - 1 end) if is_list(res), do: :lists.reverse(res), else: [] end def drop(collection, count) when count < 0 do do_drop(reverse(collection), abs(count)) |> :lists.reverse end @doc """ Drops items at the beginning of `collection` while `fun` returns a truthy value. ## Examples iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end) [3, 4, 5] """ @spec drop_while(t, (element -> as_boolean(term))) :: list def drop_while(collection, fun) when is_list(collection) do do_drop_while(collection, fun) end def drop_while(collection, fun) do {res, _} = reduce(collection, {[], true}, R.drop_while(fun)) :lists.reverse(res) end @doc """ Invokes the given `fun` for each item in the `collection`. Returns `:ok`. ## Examples Enum.each(["some", "example"], fn(x) -> IO.puts x end) "some" "example" #=> :ok """ @spec each(t, (element -> any)) :: :ok def each(collection, fun) when is_list(collection) do :lists.foreach(fun, collection) :ok end def each(collection, fun) do reduce(collection, nil, fn(entry, _) -> fun.(entry) nil end) :ok end @doc """ Returns `true` if the collection is empty, otherwise `false`. ## Examples iex> Enum.empty?([]) true iex> Enum.empty?([1, 2, 3]) false """ @spec empty?(t) :: boolean def empty?(collection) when is_list(collection) do collection == [] end def empty?(collection) do Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1) end @doc """ Finds the element at the given index (zero-based). Returns `{:ok, element}` if found, otherwise `:error`. A negative index can be passed, which means the collection is enumerated once and the index is counted from the end (i.e. `-1` fetches the last element). Note this operation takes linear time. In order to access the element at index `n`, it will need to traverse `n` previous elements. ## Examples iex> Enum.fetch([2, 4, 6], 0) {:ok, 2} iex> Enum.fetch([2, 4, 6], 2) {:ok, 6} iex> Enum.fetch([2, 4, 6], 4) :error """ @spec fetch(t, integer) :: {:ok, element} | :error def fetch(collection, n) when is_list(collection) and is_integer(n) and n >= 0 do do_fetch(collection, n) end def fetch(collection, n) when is_integer(n) and n >= 0 do res = Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) -> if acc == n do {:halt, entry} else {:cont, acc + 1} end end) case res do {:halted, entry} -> {:ok, entry} {:done, _} -> :error end end def fetch(collection, n) when is_integer(n) and n < 0 do do_fetch(reverse(collection), abs(n + 1)) end @doc """ Finds the element at the given index (zero-based). Raises `OutOfBoundsError` if the given position is outside the range of the collection. Note this operation takes linear time. In order to access the element at index `n`, it will need to traverse `n` previous elements. ## Examples iex> Enum.fetch!([2, 4, 6], 0) 2 iex> Enum.fetch!([2, 4, 6], 2) 6 iex> Enum.fetch!([2, 4, 6], 4) ** (Enum.OutOfBoundsError) out of bounds error """ @spec fetch!(t, integer) :: element | no_return def fetch!(collection, n) do case fetch(collection, n) do {:ok, h} -> h :error -> raise Enum.OutOfBoundsError end end @doc """ Filters the collection, i.e. returns only those elements for which `fun` returns a truthy value. ## Examples iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) [2] """ @spec filter(t, (element -> as_boolean(term))) :: list def filter(collection, fun) when is_list(collection) do for item <- collection, fun.(item), do: item end def filter(collection, fun) do reduce(collection, [], R.filter(fun)) |> :lists.reverse end @doc """ Filters the collection and maps its values in one pass. ## Examples iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2)) [4] """ @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list def filter_map(collection, filter, mapper) when is_list(collection) do for item <- collection, filter.(item), do: mapper.(item) end def filter_map(collection, filter, mapper) do reduce(collection, [], R.filter_map(filter, mapper)) |> :lists.reverse end @doc """ Returns the first item for which `fun` returns a truthy value. If no such item is found, returns `ifnone`. ## Examples iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end) 0 iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) 3 """ @spec find(t, default, (element -> any)) :: element | default def find(collection, ifnone \\ nil, fun) def find(collection, ifnone, fun) when is_list(collection) do do_find(collection, ifnone, fun) end def find(collection, ifnone, fun) do Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) -> if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone} end) |> elem(1) end @doc """ Similar to `find/3`, but returns the value of the function invocation instead of the element itself. ## Examples iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) true iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1) "no bools!" """ @spec find_value(t, any, (element -> any)) :: any | :nil def find_value(collection, ifnone \\ nil, fun) def find_value(collection, ifnone, fun) when is_list(collection) do do_find_value(collection, ifnone, fun) end def find_value(collection, ifnone, fun) do Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) -> fun_entry = fun.(entry) if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone} end) |> elem(1) end @doc """ Similar to `find/3`, but returns the index (zero-based) of the element instead of the element itself. ## Examples iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) 1 """ @spec find_index(t, (element -> any)) :: index | :nil def find_index(collection, fun) when is_list(collection) do do_find_index(collection, 0, fun) end def find_index(collection, fun) do res = Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) -> if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1} end) case res do {:halted, entry} -> entry {:done, _} -> nil end end @doc """ Returns a new collection appending the result of invoking `fun` on each corresponding item of `collection`. The given function should return an enumerable. ## Examples iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end) [:a, :a, :b, :b, :c, :c] iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end) [1, 2, 3, 4, 5, 6] """ @spec flat_map(t, (element -> t)) :: list def flat_map(collection, fun) do reduce(collection, [], fn(entry, acc) -> reduce(fun.(entry), acc, &[&1|&2]) end) |> :lists.reverse end @doc """ Maps and reduces a collection, flattening the given results. It expects an accumulator and a function that receives each stream item and an accumulator, and must return a tuple containing a new stream (often a list) with the new accumulator or a tuple with `:halt` as first element and the accumulator as second. ## Examples iex> enum = 1..100 iex> n = 3 iex> Enum.flat_map_reduce(enum, 0, fn i, acc -> ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc} ...> end) {[1, 2, 3], 3} """ @spec flat_map_reduce(t, acc, fun) :: {[any], any} when fun: (element, acc -> {t, acc} | {:halt, acc}), acc: any def flat_map_reduce(collection, acc, fun) do {_, {list, acc}} = Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) -> case fun.(entry, acc) do {:halt, acc} -> {:halt, {list, acc}} {[], acc} -> {:cont, {list, acc}} {[entry], acc} -> {:cont, {[entry|list], acc}} {entries, acc} -> {:cont, {reduce(entries, list, &[&1|&2]), acc}} end end) {:lists.reverse(list), acc} end @doc """ Intersperses `element` between each element of the enumeration. Complexity: O(n) ## Examples iex> Enum.intersperse([1, 2, 3], 0) [1, 0, 2, 0, 3] iex> Enum.intersperse([1], 0) [1] iex> Enum.intersperse([], 0) [] """ @spec intersperse(t, element) :: list def intersperse(collection, element) do list = reduce(collection, [], fn(x, acc) -> [x, element | acc] end) |> :lists.reverse() case list do [] -> [] [_|t] -> t # Head is a superfluous intersperser element end end @doc """ Inserts the given enumerable into a collectable. ## Examples iex> Enum.into([1, 2], [0]) [0, 1, 2] iex> Enum.into([a: 1, b: 2], %{}) %{a: 1, b: 2} """ @spec into(Enumerable.t, Collectable.t) :: Collectable.t def into(collection, list) when is_list(list) do list ++ to_list(collection) end def into(%{__struct__: _} = collection, collectable) do do_into(collection, collectable) end def into(collection, %{__struct__: _} = collectable) do do_into(collection, collectable) end def into(%{} = collection, %{} = collectable) do Map.merge(collectable, collection) end def into(collection, %{} = collectable) when is_list(collection) do Map.merge(collectable, :maps.from_list(collection)) end def into(collection, %{} = collectable) do reduce(collection, collectable, fn {k, v}, acc -> Map.put(acc, k, v) end) end def into(collection, collectable) do do_into(collection, collectable) end defp do_into(collection, collectable) do {initial, fun} = Collectable.into(collectable) into(collection, initial, fun, fn x, acc -> fun.(acc, {:cont, x}) end) end @doc """ Inserts the given enumerable into a collectable according to the transformation function. ## Examples iex> Enum.into([2, 3], [3], fn x -> x * 3 end) [3, 6, 9] """ @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do list ++ map(collection, transform) end def into(collection, collectable, transform) when is_function(transform, 1) do {initial, fun} = Collectable.into(collectable) into(collection, initial, fun, fn x, acc -> fun.(acc, {:cont, transform.(x)}) end) end defp into(collection, initial, fun, callback) do try do reduce(collection, initial, callback) catch kind, reason -> stacktrace = System.stacktrace fun.(initial, :halt) :erlang.raise(kind, reason, stacktrace) else acc -> fun.(acc, :done) end end @doc """ Joins the given `collection` into a binary using `joiner` as a separator. If `joiner` is not passed at all, it defaults to the empty binary. All items in the collection must be convertible to a binary, otherwise an error is raised. ## Examples iex> Enum.join([1, 2, 3]) "123" iex> Enum.join([1, 2, 3], " = ") "1 = 2 = 3" """ @spec join(t, String.t) :: String.t def join(collection, joiner \\ "") def join(collection, joiner) when is_binary(joiner) do reduced = reduce(collection, :first, fn entry, :first -> enum_to_string(entry) entry, acc -> [acc, joiner|enum_to_string(entry)] end) if reduced == :first do "" else IO.iodata_to_binary reduced end end @doc """ Returns a new collection, where each item is the result of invoking `fun` on each corresponding item of `collection`. For dicts, the function expects a key-value tuple. ## Examples iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end) [2, 4, 6] iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end) [a: -1, b: -2] """ @spec map(t, (element -> any)) :: list def map(collection, fun) when is_list(collection) do for item <- collection, do: fun.(item) end def map(collection, fun) do reduce(collection, [], R.map(fun)) |> :lists.reverse end @doc """ Maps and joins the given `collection` in one pass. `joiner` can be either a binary or a list and the result will be of the same type as `joiner`. If `joiner` is not passed at all, it defaults to an empty binary. All items in the collection must be convertible to a binary, otherwise an error is raised. ## Examples iex> Enum.map_join([1, 2, 3], &(&1 * 2)) "246" iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2)) "2 = 4 = 6" """ @spec map_join(t, String.t, (element -> any)) :: String.t def map_join(collection, joiner \\ "", mapper) def map_join(collection, joiner, mapper) when is_binary(joiner) do reduced = reduce(collection, :first, fn entry, :first -> enum_to_string(mapper.(entry)) entry, acc -> [acc, joiner|enum_to_string(mapper.(entry))] end) if reduced == :first do "" else IO.iodata_to_binary reduced end end @doc """ Invokes the given `fun` for each item in the `collection` while also keeping an accumulator. Returns a tuple where the first element is the mapped collection and the second one is the final accumulator. For dicts, the first tuple element must be a `{key, value}` tuple. ## Examples iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end) {[2, 4, 6], 6} """ @spec map_reduce(t, any, (element, any -> {any, any})) :: {any, any} def map_reduce(collection, acc, fun) when is_list(collection) do :lists.mapfoldl(fun, acc, collection) end def map_reduce(collection, acc, fun) do {list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) -> {new_entry, acc} = fun.(entry, acc) {[new_entry|list], acc} end) {:lists.reverse(list), acc} end @doc """ Returns the maximum value. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.max([1, 2, 3]) 3 """ @spec max(t) :: element | no_return def max(collection) do reduce(collection, &Kernel.max(&1, &2)) end @doc """ Returns the maximum value as calculated by the given function. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.max_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end) "aaa" """ @spec max_by(t, (element -> any)) :: element | no_return def max_by([h|t], fun) do reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) -> fun_entry = fun.(entry) if(fun_entry > fun_max, do: {entry, fun_entry}, else: old) end) |> elem(0) end def max_by([], _fun) do raise Enum.EmptyError end def max_by(collection, fun) do result = reduce(collection, :first, fn entry, {_, fun_max} = old -> fun_entry = fun.(entry) if(fun_entry > fun_max, do: {entry, fun_entry}, else: old) entry, :first -> {entry, fun.(entry)} end) case result do :first -> raise Enum.EmptyError {entry, _} -> entry end end @doc """ Checks if `value` exists within the `collection`. Membership is tested with the match (`===`) operator, although enumerables like ranges may include floats inside the given range. ## Examples iex> Enum.member?(1..10, 5) true iex> Enum.member?([:a, :b, :c], :d) false """ @spec member?(t, element) :: boolean def member?(collection, value) when is_list(collection) do :lists.member(value, collection) end def member?(collection, value) do case Enumerable.member?(collection, value) do {:ok, value} when is_boolean(value) -> value {:error, module} -> module.reduce(collection, {:cont, false}, fn v, _ when v === value -> {:halt, true} _, _ -> {:cont, false} end) |> elem(1) end end @doc """ Returns the minimum value. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.min([1, 2, 3]) 1 """ @spec min(t) :: element | no_return def min(collection) do reduce(collection, &Kernel.min(&1, &2)) end @doc """ Returns the minimum value as calculated by the given function. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.min_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end) "a" """ @spec min_by(t, (element -> any)) :: element | no_return def min_by([h|t], fun) do reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) -> fun_entry = fun.(entry) if(fun_entry < fun_min, do: {entry, fun_entry}, else: old) end) |> elem(0) end def min_by([], _fun) do raise Enum.EmptyError end def min_by(collection, fun) do result = reduce(collection, :first, fn entry, {_, fun_min} = old -> fun_entry = fun.(entry) if(fun_entry < fun_min, do: {entry, fun_entry}, else: old) entry, :first -> {entry, fun.(entry)} end) case result do :first -> raise Enum.EmptyError {entry, _} -> entry end end @doc """ Returns a tuple with the minimum and maximum values. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.minmax([2, 3, 1]) {1, 3} """ @spec minmax(t) :: element | no_return def minmax(collection) do result = Enum.reduce(collection, :first, fn entry, {min_value, max_value} -> {Kernel.min(entry, min_value), Kernel.max(entry, max_value)} entry, :first -> {entry, entry} end) case result do :first -> raise Enum.EmptyError result -> result end end @doc """ Returns a tuple with the minimum and maximum values as calculated by the given function. Raises `EmptyError` if the collection is empty. ## Examples iex> Enum.minmax_by(["aaa", "bb", "c"], fn(x) -> String.length(x) end) {"c", "aaa"} """ @spec minmax_by(t, (element -> any)) :: element | no_return def minmax_by(collection, fun) do result = Enum.reduce(collection, :first, fn entry, {{_, fun_min} = acc_min, {_, fun_max} = acc_max} -> fun_entry = fun.(entry) if fun_entry < fun_min, do: acc_min = {entry, fun_entry} if fun_entry > fun_max, do: acc_max = {entry, fun_entry} {acc_min, acc_max} entry, :first -> fun_entry = fun.(entry) {{entry, fun_entry}, {entry, fun_entry}} end) case result do :first -> raise Enum.EmptyError {{min_entry, _}, {max_entry, _}} -> {min_entry, max_entry} end end @doc """ Returns the sum of all values. Raises `ArithmeticError` if collection contains a non-numeric value. ## Examples iex> Enum.sum([1, 2, 3]) 6 """ @spec sum(t) :: number def sum(collection) do reduce(collection, 0, &+/2) end @doc """ Partitions `collection` into two collections, where the first one contains elements for which `fun` returns a truthy value, and the second one -- for which `fun` returns `false` or `nil`. ## Examples iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) {[2], [1, 3]} """ @spec partition(t, (element -> any)) :: {list, list} def partition(collection, fun) do {acc1, acc2} = reduce(collection, {[], []}, fn(entry, {acc1, acc2}) -> if fun.(entry) do {[entry|acc1], acc2} else {acc1, [entry|acc2]} end end) {:lists.reverse(acc1), :lists.reverse(acc2)} end @doc """ Splits `collection` into groups based on `fun`. The result is a dict (by default a map) where each key is a group and each value is a list of elements from `collection` for which `fun` returned that group. Ordering is not necessarily preserved. ## Examples iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1) %{3 => ["cat", "ant"], 7 => ["buffalo"], 5 => ["dingo"]} """ @spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t def group_by(collection, dict \\ %{}, fun) do reduce(collection, dict, fn(entry, categories) -> Dict.update(categories, fun.(entry), [entry], &[entry|&1]) end) end @doc """ Invokes `fun` for each element in the collection passing that element and the accumulator `acc` as arguments. `fun`'s return value is stored in `acc`. Returns the accumulator. ## Examples iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end) 6 """ @spec reduce(t, any, (element, any -> any)) :: any def reduce(collection, acc, fun) when is_list(collection) do :lists.foldl(fun, acc, collection) end def reduce(%{__struct__: _} = collection, acc, fun) do Enumerable.reduce(collection, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1) end def reduce(%{} = collection, acc, fun) do :maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, collection) end def reduce(collection, acc, fun) do Enumerable.reduce(collection, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1) end @doc """ Invokes `fun` for each element in the collection passing that element and the accumulator `acc` as arguments. `fun`'s return value is stored in `acc`. The first element of the collection is used as the initial value of `acc`. Returns the accumulator. ## Examples iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end) 24 """ @spec reduce(t, (element, any -> any)) :: any def reduce([h|t], fun) do reduce(t, h, fun) end def reduce([], _fun) do raise Enum.EmptyError end def reduce(collection, fun) do result = Enumerable.reduce(collection, {:cont, :first}, fn x, :first -> {:cont, {:acc, x}} x, {:acc, acc} -> {:cont, {:acc, fun.(x, acc)}} end) |> elem(1) case result do :first -> raise Enum.EmptyError {:acc, acc} -> acc end end @doc """ Returns elements of collection for which `fun` returns `false` or `nil`. ## Examples iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) [1, 3] """ @spec reject(t, (element -> as_boolean(term))) :: list def reject(collection, fun) when is_list(collection) do for item <- collection, !fun.(item), do: item end def reject(collection, fun) do reduce(collection, [], R.reject(fun)) |> :lists.reverse end @doc """ Reverses the collection. ## Examples iex> Enum.reverse([1, 2, 3]) [3, 2, 1] """ @spec reverse(t) :: list def reverse(collection) when is_list(collection) do :lists.reverse(collection) end def reverse(collection) do reverse(collection, []) end @doc """ Reverses the collection and appends the tail. This is an optimization for `Enum.concat(Enum.reverse(collection), tail)`. ## Examples iex> Enum.reverse([1, 2, 3], [4, 5, 6]) [3, 2, 1, 4, 5, 6] """ @spec reverse(t, t) :: list def reverse(collection, tail) when is_list(collection) and is_list(tail) do :lists.reverse(collection, tail) end def reverse(collection, tail) do reduce(collection, to_list(tail), fn(entry, acc) -> [entry|acc] end) end @doc """ Reverses the collection in the range from initial position `first` through `count` elements. If `count` is greater than the size of the rest of the collection, then this function will reverse the rest of the collection. ## Examples iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4) [1, 2, 6, 5, 4, 3] """ @spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list def reverse_slice(collection, start, count) when start >= 0 and count >= 0 do list = reverse(collection) length = length(list) count = Kernel.min(count, length - start) if count > 0 do reverse_slice(list, length, start + count, count, []) else :lists.reverse(list) end end @doc """ Returns a random element of a collection. Raises `EmptyError` if the collection is empty. Notice that you need to explicitly call `:random.seed/1` and set a seed value for the random algorithm. Otherwise, the default seed will be set which will always return the same result. For example, one could do the following to set a seed dynamically: :random.seed(:os.timestamp) The implementation is based on the [reservoir sampling](http://en.wikipedia.org/wiki/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle) algorithm. It assumes that the sample being returned can fit into memory; the input collection doesn't have to - it is traversed just once. ## Examples iex> Enum.random([1, 2, 3]) 1 iex> Enum.random([1, 2, 3]) 2 """ @spec random(t) :: element def random(collection) do case random(collection, 1) do [] -> raise Enum.EmptyError [e] -> e end end @doc """ Returns a random sublist of a collection. Notice this function will traverse the whole collection to get the random sublist of collection. If you want the random number between two integers, the best option is to use the :random module. See `random/1` for notes on implementation and random seed. ## Examples iex> Enum.random(1..10, 2) [1, 5] iex> Enum.random(?a..?z, 5) 'tfesm' """ @spec random(t, integer) :: list def random(collection, count) when count > 0 do sample = Tuple.duplicate(nil, count) reducer = fn x, {i, sample} -> j = random_index(i) if i < count do swapped = sample |> elem(j) {i + 1, sample |> put_elem(i, swapped) |> put_elem(j, x)} else if j < count, do: sample = sample |> put_elem(j, x) {i + 1, sample} end end {n, sample} = reduce(collection, {0, sample}, reducer) sample |> Tuple.to_list |> take(Kernel.min(count, n)) end def random(_collection, 0), do: [] @doc """ Applies the given function to each element in the collection, storing the result in a list and passing it as the accumulator for the next computation. ## Examples iex> Enum.scan(1..5, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, (element, any -> any)) :: list def scan(enum, fun) do {res, _} = reduce(enum, {[], :first}, R.scan_2(fun)) :lists.reverse(res) end @doc """ Applies the given function to each element in the collection, storing the result in a list and passing it as the accumulator for the next computation. Uses the given `acc` as the starting value. ## Examples iex> Enum.scan(1..5, 0, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, any, (element, any -> any)) :: list def scan(enum, acc, fun) do {res, _} = reduce(enum, {[], acc}, R.scan_3(fun)) :lists.reverse(res) end @doc """ Returns a list of collection elements shuffled. Notice that you need to explicitly call `:random.seed/1` and set a seed value for the random algorithm. Otherwise, the default seed will be set which will always return the same result. For example, one could do the following to set a seed dynamically: :random.seed(:os.timestamp) ## Examples iex> Enum.shuffle([1, 2, 3]) [3, 2, 1] iex> Enum.shuffle([1, 2, 3]) [3, 1, 2] """ @spec shuffle(t) :: list def shuffle(collection) do randomized = reduce(collection, [], fn x, acc -> [{:random.uniform, x}|acc] end) unwrap(:lists.keysort(1, randomized), []) end @doc """ Returns a subset list of the given collection. Drops elements until element position `start`, then takes `count` elements. If the count is greater than collection length, it returns as much as possible. If zero, then it returns `[]`. ## Examples iex> Enum.slice(1..100, 5, 10) [6, 7, 8, 9, 10, 11, 12, 13, 14, 15] iex> Enum.slice(1..10, 5, 100) [6, 7, 8, 9, 10] iex> Enum.slice(1..10, 5, 0) [] """ @spec slice(t, integer, non_neg_integer) :: list def slice(_collection, _start, 0), do: [] def slice(collection, start, count) when start < 0 do {list, new_start} = enumerate_and_count(collection, start) if new_start >= 0 do slice(list, new_start, count) else [] end end def slice(collection, start, count) when is_list(collection) and start >= 0 and count > 0 do do_slice(collection, start, count) end def slice(collection, start, count) when start >= 0 and count > 0 do {_, _, list} = Enumerable.reduce(collection, {:cont, {start, count, []}}, fn _entry, {start, count, _list} when start > 0 -> {:cont, {start-1, count, []}} entry, {start, count, list} when count > 1 -> {:cont, {start, count-1, [entry|list]}} entry, {start, count, list} -> {:halt, {start, count, [entry|list]}} end) |> elem(1) :lists.reverse(list) end @doc """ Returns a subset list of the given collection. Drops elements until element position `range.first`, then takes elements until element position `range.last` (inclusive). Positions are calculated by adding the number of items in the collection to negative positions (so position -3 in a collection with count 5 becomes position 2). The first position (after adding count to negative positions) must be smaller or equal to the last position. If the start of the range is not a valid offset for the given collection or if the range is in reverse order, returns `[]`. ## Examples iex> Enum.slice(1..100, 5..10) [6, 7, 8, 9, 10, 11] iex> Enum.slice(1..10, 5..20) [6, 7, 8, 9, 10] iex> Enum.slice(1..10, 11..20) [] iex> Enum.slice(1..10, 6..5) [] """ @spec slice(t, Range.t) :: list def slice(collection, range) def slice(collection, first..last) when first >= 0 and last >= 0 do # Simple case, which works on infinite collections if last - first >= 0 do slice(collection, first, last - first + 1) else [] end end def slice(collection, first..last) do {list, count} = enumerate_and_count(collection, 0) corr_first = if first >= 0, do: first, else: first + count corr_last = if last >= 0, do: last, else: last + count length = corr_last - corr_first + 1 if corr_first >= 0 and length > 0 do slice(list, corr_first, length) else [] end end @doc """ Sorts the collection according to Elixir's term ordering. Uses the merge sort algorithm. ## Examples iex> Enum.sort([3, 2, 1]) [1, 2, 3] """ @spec sort(t) :: list def sort(collection) when is_list(collection) do :lists.sort(collection) end def sort(collection) do sort(collection, &(&1 <= &2)) end @doc """ Sorts the collection by the given function. This function uses the merge sort algorithm. The given function must return `false` if the first argument is less than right one. ## Examples iex> Enum.sort([1, 2, 3], &(&1 > &2)) [3, 2, 1] The sorting algorithm will be stable as long as the given function returns `true` for values considered equal: iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2)) ["of", "some", "kind", "monster"] If the function does not return `true` for equal values, the sorting is not stable and the order of equal terms may be shuffled: iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2)) ["of", "kind", "some", "monster"] """ @spec sort(t, (element, element -> boolean)) :: list def sort(collection, fun) when is_list(collection) do :lists.sort(fun, collection) end def sort(collection, fun) do reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun) end @doc """ Sorts the mapped results of the `collection` according to the `sorter` function. This function maps each element of the collection using the `mapper` function. The collection is then sorted by the mapped elements using the `sorter` function, which defaults to `<=/2` `sort_by/3` differs from `sort/2` in that it only calculates the comparison value for each element in the collection once instead of once for each element in each comparison. If the same function is being called on both element, it's also more compact to use `sort_by/3`. This technique is also known as a [Schwartzian Transform](https://en.wikipedia.org/wiki/Schwartzian_transform), or the Lisp decorate-sort-undecorate idiom as the `mapper` is decorating the original `collection`, then `sorter` is sorting the decorations, and finally the `collection` is being undecorated so only the original elements remain, but now in sorted order. ## Examples Using the default `sorter` of `<=/2`: iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1 ["of", "some", "kind", "monster"] Using a custom `sorter` to override the order: iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1, &>=/2 ["monster", "some", "kind", "of"] """ @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element def sort_by(collection, mapper, sorter \\ &<=/2) do collection |> map(&{&1, mapper.(&1)}) |> sort(&sorter.(elem(&1, 1), elem(&2, 1))) |> map(&elem(&1, 0)) end @doc """ Splits the enumerable into two collections, leaving `count` elements in the first one. If `count` is a negative number, it starts counting from the back to the beginning of the collection. Be aware that a negative `count` implies the collection will be enumerated twice: once to calculate the position, and a second time to do the actual splitting. ## Examples iex> Enum.split([1, 2, 3], 2) {[1, 2], [3]} iex> Enum.split([1, 2, 3], 10) {[1, 2, 3], []} iex> Enum.split([1, 2, 3], 0) {[], [1, 2, 3]} iex> Enum.split([1, 2, 3], -1) {[1, 2], [3]} iex> Enum.split([1, 2, 3], -5) {[], [1, 2, 3]} """ @spec split(t, integer) :: {list, list} def split(collection, count) when is_list(collection) and count >= 0 do do_split(collection, count, []) end def split(collection, count) when count >= 0 do {_, list1, list2} = reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) -> if counter > 0 do {counter - 1, [entry|acc1], acc2} else {counter, acc1, [entry|acc2]} end end) {:lists.reverse(list1), :lists.reverse(list2)} end def split(collection, count) when count < 0 do do_split_reverse(reverse(collection), abs(count), []) end @doc """ Splits `collection` in two at the position of the element for which `fun` returns `false` for the first time. ## Examples iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end) {[1, 2], [3, 4]} """ @spec split_while(t, (element -> as_boolean(term))) :: {list, list} def split_while(collection, fun) when is_list(collection) do do_split_while(collection, fun, []) end def split_while(collection, fun) do {list1, list2} = reduce(collection, {[], []}, fn entry, {acc1, []} -> if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]}) entry, {acc1, acc2} -> {acc1, [entry|acc2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Takes the first `count` items from the collection. `count` must be an integer. If a negative `count` is given, the last `count` values will be taken. For such, the collection is fully enumerated keeping up to `2 * count` elements in memory. Once the end of the collection is reached, the last `count` elements are returned. ## Examples iex> Enum.take([1, 2, 3], 2) [1, 2] iex> Enum.take([1, 2, 3], 10) [1, 2, 3] iex> Enum.take([1, 2, 3], 0) [] iex> Enum.take([1, 2, 3], -1) [3] """ @spec take(t, integer) :: list def take(_collection, 0), do: [] def take([], _count), do: [] def take(collection, n) when is_list(collection) and is_integer(n) and n > 0 do do_take(collection, n) end def take(collection, n) when is_integer(n) and n > 0 do {_, {res, _}} = Enumerable.reduce(collection, {:cont, {[], n}}, fn(entry, {list, count}) -> case count do 0 -> {:halt, {list, count}} 1 -> {:halt, {[entry|list], count - 1}} _ -> {:cont, {[entry|list], count - 1}} end end) :lists.reverse(res) end def take(collection, n) when is_integer(n) and n < 0 do n = abs(n) {_count, buf1, buf2} = reduce(collection, {0, [], []}, fn entry, {count, buf1, buf2} -> buf1 = [entry|buf1] count = count + 1 if count == n do {0, [], buf1} else {count, buf1, buf2} end end) do_take_last(buf1, buf2, n, []) end defp do_take_last(_buf1, _buf2, 0, acc), do: acc defp do_take_last([], [], _, acc), do: acc defp do_take_last([], [h|t], n, acc), do: do_take_last([], t, n-1, [h|acc]) defp do_take_last([h|t], buf2, n, acc), do: do_take_last(t, buf2, n-1, [h|acc]) @doc """ Returns a collection of every `nth` item in the collection, starting with the first element. The second argument specifying every `nth` item must be a non-negative integer. ## Examples iex> Enum.take_every(1..10, 2) [1, 3, 5, 7, 9] """ @spec take_every(t, non_neg_integer) :: list def take_every(_collection, 0), do: [] def take_every([], _nth), do: [] def take_every(collection, nth) when is_integer(nth) and nth > 0 do {res, _} = reduce(collection, {[], :first}, R.take_every(nth)) :lists.reverse(res) end @doc """ Takes the items from the beginning of `collection` while `fun` returns a truthy value. ## Examples iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end) [1, 2] """ @spec take_while(t, (element -> as_boolean(term))) :: list def take_while(collection, fun) when is_list(collection) do do_take_while(collection, fun) end def take_while(collection, fun) do {_, res} = Enumerable.reduce(collection, {:cont, []}, fn(entry, acc) -> if fun.(entry) do {:cont, [entry|acc]} else {:halt, acc} end end) :lists.reverse(res) end @doc """ Converts `collection` to a list. ## Examples iex> Enum.to_list(1 .. 3) [1, 2, 3] """ @spec to_list(t) :: [term] def to_list(collection) when is_list(collection) do collection end def to_list(collection) do reverse(collection) |> :lists.reverse end @doc """ Enumerates the collection, removing all duplicated elements. ## Examples iex> Enum.uniq([1, 2, 3, 3, 2, 1]) |> Enum.to_list [1, 2, 3] """ @spec uniq(t) :: list def uniq(collection) do uniq_by(collection, fn x -> x end) end # TODO: Deprecate by 1.2 # TODO: Remove by 2.0 @doc false def uniq(collection, fun) do uniq_by(collection, fun) end @doc """ Enumerates the collection, removing all duplicated elements. ## Example iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end) [{1, :x}, {2, :y}] """ @spec uniq_by(t, (element -> term)) :: list def uniq_by(collection, fun) when is_list(collection) do do_uniq(collection, HashSet.new, fun) end def uniq_by(collection, fun) do {list, _} = reduce(collection, {[], HashSet.new}, R.uniq(fun)) :lists.reverse(list) end @doc """ Opposite of `Enum.zip/2`; takes a list of two-element tuples and returns a tuple with two lists, each of which is formed by the first and second element of each tuple, respectively. This function fails unless `collection` is or can be converted into a list of tuples with *exactly* two elements in each tuple. ## Examples iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}]) {[:a, :b, :c], [1, 2, 3]} iex> Enum.unzip(%{a: 1, b: 2}) {[:a, :b], [1, 2]} """ @spec unzip(t) :: {list(element), list(element)} def unzip(collection) do {list1, list2} = reduce(collection, {[], []}, fn({el1, el2}, {list1, list2}) -> {[el1|list1], [el2|list2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Zips corresponding elements from two collections into one list of tuples. The zipping finishes as soon as any enumerable completes. ## Examples iex> Enum.zip([1, 2, 3], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] """ @spec zip(t, t) :: [{any, any}] def zip(collection1, collection2) when is_list(collection1) and is_list(collection2) do do_zip(collection1, collection2) end def zip(collection1, collection2) do Stream.zip(collection1, collection2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse end @doc """ Returns the collection with each element wrapped in a tuple alongside its index. ## Examples iex> Enum.with_index [1, 2, 3] [{1, 0}, {2, 1}, {3, 2}] """ @spec with_index(t) :: list({element, non_neg_integer}) def with_index(collection) do map_reduce(collection, 0, fn x, acc -> {{x, acc}, acc + 1} end) |> elem(0) end ## Helpers @compile {:inline, enum_to_string: 1} defp enumerate_and_count(collection, count) when is_list(collection) do {collection, length(collection) - abs(count)} end defp enumerate_and_count(collection, count) do map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end) end defp enum_to_string(entry) when is_binary(entry), do: entry defp enum_to_string(entry), do: String.Chars.to_string(entry) defp random_index(n) do :random.uniform(n + 1) - 1 end ## Implementations ## all? defp do_all?([h|t], fun) do if fun.(h) do do_all?(t, fun) else false end end defp do_all?([], _) do true end ## any? defp do_any?([h|t], fun) do if fun.(h) do true else do_any?(t, fun) end end defp do_any?([], _) do false end ## fetch defp do_fetch([h|_], 0), do: {:ok, h} defp do_fetch([_|t], n), do: do_fetch(t, n - 1) defp do_fetch([], _), do: :error ## drop defp do_drop([_|t], counter) when counter > 0 do do_drop(t, counter - 1) end defp do_drop(list, 0) do list end defp do_drop([], _) do [] end ## drop_while defp do_drop_while([h|t], fun) do if fun.(h) do do_drop_while(t, fun) else [h|t] end end defp do_drop_while([], _) do [] end ## find defp do_find([h|t], ifnone, fun) do if fun.(h) do h else do_find(t, ifnone, fun) end end defp do_find([], ifnone, _) do ifnone end ## find_index defp do_find_index([h|t], counter, fun) do if fun.(h) do counter else do_find_index(t, counter + 1, fun) end end defp do_find_index([], _, _) do nil end ## find_value defp do_find_value([h|t], ifnone, fun) do fun.(h) || do_find_value(t, ifnone, fun) end defp do_find_value([], ifnone, _) do ifnone end ## shuffle defp unwrap([{_, h} | collection], t) do unwrap(collection, [h|t]) end defp unwrap([], t), do: t ## sort defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do cond do fun.(y, entry) == bool -> {:split, entry, y, [x|r], rs, bool} fun.(x, entry) == bool -> {:split, y, entry, [x|r], rs, bool} r == [] -> {:split, y, x, [entry], rs, bool} true -> {:pivot, y, x, r, rs, entry, bool} end end defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do cond do fun.(y, entry) == bool -> {:pivot, entry, y, [x | r], rs, s, bool} fun.(x, entry) == bool -> {:pivot, y, entry, [x | r], rs, s, bool} fun.(s, entry) == bool -> {:split, entry, s, [], [[y, x | r] | rs], bool} true -> {:split, s, entry, [], [[y, x | r] | rs], bool} end end defp sort_reducer(entry, [x], fun) do {:split, entry, x, [], [], fun.(x, entry)} end defp sort_reducer(entry, acc, _fun) do [entry|acc] end defp sort_terminator({:split, y, x, r, rs, bool}, fun) do sort_merge([[y, x | r] | rs], fun, bool) end defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do sort_merge([[s], [y, x | r] | rs], fun, bool) end defp sort_terminator(acc, _fun) do acc end defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true) defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false) defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do: sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true) defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do: sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false) defp sort_merge([l], [], _fun, _bool), do: l defp sort_merge([l], acc, fun, bool), do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool) defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do: reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true) defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do: reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false) defp reverse_sort_merge([l], acc, fun, bool), do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool) defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do if fun.(h1, h2) == bool do sort_merge_2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge_1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge_1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m]) defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do if fun.(h1, h2) == bool do sort_merge_2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge_1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge_2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m]) ## reverse_slice defp reverse_slice(rest, idx, idx, count, acc) do {slice, rest} = head_slice(rest, count, []) :lists.reverse(rest, :lists.reverse(slice, acc)) end defp reverse_slice([elem | rest], idx, start, count, acc) do reverse_slice(rest, idx - 1, start, count, [elem | acc]) end defp head_slice(rest, 0, acc), do: {acc, rest} defp head_slice([elem | rest], count, acc) do head_slice(rest, count - 1, [elem | acc]) end ## split defp do_split([h|t], counter, acc) when counter > 0 do do_split(t, counter - 1, [h|acc]) end defp do_split(list, 0, acc) do {:lists.reverse(acc), list} end defp do_split([], _, acc) do {:lists.reverse(acc), []} end defp do_split_reverse([h|t], counter, acc) when counter > 0 do do_split_reverse(t, counter - 1, [h|acc]) end defp do_split_reverse(list, 0, acc) do {:lists.reverse(list), acc} end defp do_split_reverse([], _, acc) do {[], acc} end ## split_while defp do_split_while([h|t], fun, acc) do if fun.(h) do do_split_while(t, fun, [h|acc]) else {:lists.reverse(acc), [h|t]} end end defp do_split_while([], _, acc) do {:lists.reverse(acc), []} end ## take defp do_take([h|t], counter) when counter > 0 do [h|do_take(t, counter - 1)] end defp do_take(_list, 0) do [] end defp do_take([], _) do [] end ## take_while defp do_take_while([h|t], fun) do if fun.(h) do [h|do_take_while(t, fun)] else [] end end defp do_take_while([], _) do [] end ## uniq defp do_uniq([h|t], acc, fun) do fun_h = fun.(h) if HashSet.member?(acc, fun_h) do do_uniq(t, acc, fun) else [h|do_uniq(t, HashSet.put(acc, fun_h), fun)] end end defp do_uniq([], _acc, _fun) do [] end ## zip defp do_zip([h1|next1], [h2|next2]) do [{h1, h2}|do_zip(next1, next2)] end defp do_zip(_, []), do: [] defp do_zip([], _), do: [] ## slice defp do_slice([], _start, _count) do [] end defp do_slice(_list, _start, 0) do [] end defp do_slice([h|t], 0, count) do [h|do_slice(t, 0, count-1)] end defp do_slice([_|t], start, count) do do_slice(t, start-1, count) end end defimpl Enumerable, for: List do def reduce(_, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun) def member?(_list, _value), do: {:error, __MODULE__} def count(_list), do: {:error, __MODULE__} end defimpl Enumerable, for: Map do def reduce(map, acc, fun) do do_reduce(:maps.to_list(map), acc, fun) end defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc} defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)} defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc} defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun) def member?(map, {key, value}) do {:ok, match?({:ok, ^value}, :maps.find(key, map))} end def member?(_map, _other) do {:ok, false} end def count(map) do {:ok, map_size(map)} end end defimpl Enumerable, for: Function do def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun) def member?(_function, _value), do: {:error, __MODULE__} def count(_function), do: {:error, __MODULE__} end
25.623497
129
0.599927
f759fdcea46a64b8d9dc5f8f58c9978226d2095a
217
exs
Elixir
apps/activity_logger/config/test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/activity_logger/config/test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/activity_logger/config/test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
use Mix.Config config :activity_logger, ActivityLogger.Repo, pool: Ecto.Adapters.SQL.Sandbox, url: {:system, "DATABASE_URL", "postgres://localhost/ewallet_test"}, queue_target: 10_000, queue_interval: 60_000
27.125
70
0.760369
f75a297a3082fccbeea8b67ce1a7274b8963db21
21,770
ex
Elixir
lib/console_web/controllers/label_controller.ex
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
null
null
null
lib/console_web/controllers/label_controller.ex
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
1
2021-04-03T09:29:31.000Z
2021-04-03T09:29:31.000Z
lib/console_web/controllers/label_controller.ex
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
null
null
null
defmodule ConsoleWeb.LabelController do use ConsoleWeb, :controller alias Console.Repo alias Console.Labels alias Console.Devices alias Console.Channels alias Console.Functions alias Console.Labels.Label plug ConsoleWeb.Plug.AuthorizeAction action_fallback(ConsoleWeb.FallbackController) def create(conn, %{"label" => label_params}) do current_organization = conn.assigns.current_organization current_user = conn.assigns.current_user label_params = Map.merge(label_params, %{ "organization_id" => current_organization.id, "creator" => current_user.email }) with {:ok, %Label{} = label} <- Labels.create_label(current_organization, label_params) do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) case label_params["channel_id"] do nil -> nil id -> channel = Ecto.assoc(current_organization, :channels) |> Repo.get!(id) Labels.add_labels_to_channel([label.id], channel, current_organization) end case label_params["function_id"] do nil -> nil id -> function = Functions.get_function!(current_organization, id) ConsoleWeb.Endpoint.broadcast("graphql:function_show", "graphql:function_show:#{function.id}:function_update", %{}) end conn |> put_status(:created) |> put_resp_header("message", "Label #{label.name} added successfully") |> render("show.json", label: label) end end def update(conn, %{"id" => id, "label" => label_params}) do current_organization = conn.assigns.current_organization label = Labels.get_label!(current_organization, id) name = label.name function = case label_params["function_id"] do nil -> false id -> Functions.get_function!(current_organization, id) end with {:ok, %Label{} = label} <- Labels.update_label(label, label_params) do ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{label.id}:label_update", %{}) if function, do: ConsoleWeb.Endpoint.broadcast("graphql:function_show", "graphql:function_show:#{function.id}:function_update", %{}) broadcast_router_update_devices(label) msg = cond do function -> "Label #{label.name} added to function successfully" label.name == name -> "Label #{label.name} updated successfully" true -> "The label #{name} was successfully updated to #{label.name}" end conn |> put_resp_header("message", msg) |> render("show.json", label: label) end end def delete(conn, %{"id" => id}) do current_organization = conn.assigns.current_organization label = Labels.get_label!(current_organization, id) |> Labels.fetch_assoc([:devices]) with {:ok, %Label{} = label} <- Labels.delete_label(label) do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) broadcast_router_update_devices(label.devices) conn |> put_resp_header("message", "#{label.name} deleted successfully") |> send_resp(:no_content, "") end end def delete(conn, %{"labels" => labels}) do current_organization = conn.assigns.current_organization labels_to_delete = Labels.get_labels(current_organization, labels) |> Labels.multi_fetch_assoc([:devices]) assoc_devices = Enum.map(labels_to_delete, fn l -> l.devices end) |> List.flatten() |> Enum.uniq() with {:ok, _} <- Labels.delete_labels(labels, current_organization.id) do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) broadcast_router_update_devices(assoc_devices) conn |> put_resp_header("message", "Labels deleted successfully") |> send_resp(:no_content, "") end end def add_devices_to_label(conn, %{"devices" => devices, "labels" => labels, "to_label" => to_label}) do current_organization = conn.assigns.current_organization destination_label = Labels.get_label!(current_organization, to_label) if length(devices) == 0 and length(labels) == 0 do {:error, :bad_request, "Please select a device or label"} else with {:ok, count, devices_labels} <- Labels.add_devices_to_label(devices, labels, destination_label.id, current_organization) do msg = case count do 0 -> "All selected devices are already in label" _ -> "#{count} Devices added to label successfully" end ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{destination_label.id}:label_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show_table", "graphql:label_show_table:#{destination_label.id}:update_label_devices", %{}) assoc_devices = devices_labels |> Enum.map(fn dl -> dl.device_id end) ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => assoc_devices }) conn |> put_resp_header("message", msg) |> send_resp(:no_content, "") end end end def add_devices_to_label(conn, %{"devices" => devices, "to_label" => to_label}) do current_organization = conn.assigns.current_organization apply_label_to_devices(devices, to_label, current_organization, conn) end def add_devices_to_label(conn, %{"devices" => devices, "new_label" => label_name}) do current_organization = conn.assigns.current_organization current_user = conn.assigns.current_user create_label_and_apply_to_devices(devices, label_name, current_organization, current_user, conn) end def add_devices_to_label(conn, %{"to_label" => to_label}) do conn.assigns.current_organization.id |> Devices.get_devices() |> Enum.map(fn device -> device.id end) |> apply_label_to_devices(to_label, conn.assigns.current_organization, conn) end def add_devices_to_label(conn, %{"new_label" => label_name}) do conn.assigns.current_organization.id |> Devices.get_devices() |> Enum.map(fn device -> device.id end) |> create_label_and_apply_to_devices( label_name, conn.assigns.current_organization, conn.assigns.current_user, conn ) end def add_labels_to_channel(conn, %{"labels" => labels, "channel_id" => channel_id}) do current_organization = conn.assigns.current_organization channel = Ecto.assoc(current_organization, :channels) |> Repo.get(channel_id) with {:ok, count, _first_label} <- Labels.add_labels_to_channel(labels, channel, current_organization) do msg = case count do 0 -> "All selected labels are already in integration" _ -> ConsoleWeb.Endpoint.broadcast("graphql:channel_show", "graphql:channel_show:#{channel.id}:channel_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) labels_updated = Labels.get_labels(current_organization, labels) |> Labels.multi_fetch_assoc([:devices]) assoc_devices = Enum.map(labels_updated, fn l -> l.devices end) |> List.flatten() |> Enum.uniq() broadcast_router_update_devices(assoc_devices) "#{count} Labels added to integration successfully" end conn |> put_resp_header("message", msg) |> send_resp(:no_content, "") end end def add_labels_to_channel(conn, %{"label_id" => label_id, "channel_id" => channel_id}) do # used for labelShowChannelsAttached current_organization = conn.assigns.current_organization channel = Ecto.assoc(current_organization, :channels) |> Repo.get(channel_id) with {:ok, 1, label} <- Labels.add_labels_to_channel([label_id], channel, current_organization) do ConsoleWeb.Endpoint.broadcast("graphql:channel_show", "graphql:channel_show:#{channel.id}:channel_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{label.id}:label_update", %{}) broadcast_router_update_devices(label) conn |> put_resp_header("message", "Integration added to label successfully") |> send_resp(:no_content, "") end end def delete_devices_from_labels(conn, %{"devices" => devices, "label_id" => label_id}) do current_organization = conn.assigns.current_organization with {_, nil} <- Labels.delete_devices_from_label(devices, label_id, current_organization) do label = Labels.get_label!(label_id) ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{label.id}:label_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show_table", "graphql:label_show_table:#{label.id}:update_label_devices", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => devices }) conn |> put_resp_header("message", "Device(s) successfully removed from label") |> send_resp(:no_content, "") end end def delete_devices_from_labels(conn, %{"labels" => labels, "device_id" => device_id}) do current_organization = conn.assigns.current_organization with {_, nil} <- Labels.delete_labels_from_device(labels, device_id, current_organization) do device = Devices.get_device!(device_id) ConsoleWeb.Endpoint.broadcast("graphql:devices_index_table", "graphql:devices_index_table:#{current_organization.id}:device_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => [device.id] }) ConsoleWeb.Endpoint.broadcast("graphql:device_show", "graphql:device_show:#{device.id}:device_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:device_show_labels_table", "graphql:device_show_labels_table:#{device.id}:device_update", %{}) conn |> put_resp_header("message", "Label(s) successfully removed from device") |> send_resp(:no_content, "") end end def delete_devices_from_labels(conn, %{"devices" => devices}) do current_organization = conn.assigns.current_organization with {:ok, devices} <- Labels.delete_all_labels_from_devices(devices, current_organization) do ConsoleWeb.Endpoint.broadcast("graphql:devices_index_table", "graphql:devices_index_table:#{current_organization.id}:device_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) broadcast_router_update_devices(devices) conn |> put_resp_header("message", "All labels successfully removed from devices") |> send_resp(:no_content, "") end end def delete_devices_from_labels(conn, %{"labels" => labels}) do current_organization = conn.assigns.current_organization with {:ok, labels} <- Labels.delete_all_devices_from_labels(labels, current_organization) do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) assoc_labels = labels |> Labels.multi_fetch_assoc([:devices]) assoc_devices = Enum.map(assoc_labels, fn l -> l.devices end) |> List.flatten() |> Enum.uniq() broadcast_router_update_devices(assoc_devices) conn |> put_resp_header("message", "All devices successfully removed from labels") |> send_resp(:no_content, "") end end def delete_devices_from_labels(conn, _params) do current_organization = conn.assigns.current_organization Labels.delete_all_labels_from_devices_for_org(current_organization) ConsoleWeb.Endpoint.broadcast("graphql:devices_index_table", "graphql:devices_index_table:#{current_organization.id}:device_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) conn |> put_resp_header("message", "All devices successfully removed from labels") |> send_resp(:no_content, "") end def delete_labels_from_channel(conn, %{"labels" => labels, "channel_id" => channel_id}) do current_organization = conn.assigns.current_organization with {_, nil} <- Labels.delete_labels_from_channel(labels, channel_id, current_organization) do channel = Channels.get_channel!(channel_id) ConsoleWeb.Endpoint.broadcast("graphql:channel_show", "graphql:channel_show:#{channel.id}:channel_update", %{}) assoc_labels = Labels.get_labels(current_organization, labels) |> Labels.multi_fetch_assoc([:devices]) assoc_devices = Enum.map(assoc_labels, fn l -> l.devices end) |> List.flatten() |> Enum.uniq() broadcast_router_update_devices(assoc_devices) conn |> put_resp_header("message", "Label(s) successfully removed from integration") |> send_resp(:no_content, "") end end def delete_labels_from_channel(conn, %{"label_id" => label_id, "channel_id" => channel_id}) do current_organization = conn.assigns.current_organization with {_, nil} <- Labels.delete_labels_from_channel([label_id], channel_id, current_organization) do channel = Channels.get_channel!(channel_id) ConsoleWeb.Endpoint.broadcast("graphql:channel_show", "graphql:channel_show:#{channel.id}:channel_update", %{}) label = Labels.get_label!(current_organization, label_id) ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{label.id}:label_update", %{}) broadcast_router_update_devices(label) conn |> put_resp_header("message", "Integration successfully removed from label") |> send_resp(:no_content, "") end end def remove_function(conn, %{ "label" => label_id, "function" => function_id }) do current_organization = conn.assigns.current_organization label = Labels.get_label!(current_organization, label_id) if label.function_id == function_id do with {:ok, _} <- Labels.update_label(label, %{ "function_id" => nil }) do function = Functions.get_function!(current_organization, function_id) ConsoleWeb.Endpoint.broadcast("graphql:function_index_table", "graphql:function_index_table:#{current_organization.id}:function_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:function_show", "graphql:function_show:#{function.id}:function_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show", "graphql:label_show:#{label.id}:label_update", %{}) broadcast_router_update_devices(label) conn |> put_resp_header("message", "Function successfully removed from label") |> send_resp(:no_content, "") end else {:error, :not_found, "Function not found on label"} end end def debug(conn, %{"label" => label_id}) do current_organization = conn.assigns.current_organization label = Labels.get_label!(current_organization, label_id) label = Labels.fetch_assoc(label, [:devices]) devices = label.devices |> Enum.map(fn d -> d.id end) if length(devices) > 0 do ConsoleWeb.Endpoint.broadcast("device:all", "device:all:debug:devices", %{ "devices" => devices }) end conn |> send_resp(:no_content, "") end def swap_label(conn, %{ "label_id" => label_id, "destination_label_id" => destination_label_id }) do current_organization = conn.assigns.current_organization label = Labels.get_label!(current_organization, label_id) |> Labels.fetch_assoc([:devices]) destination_label = Labels.get_label!(current_organization, destination_label_id) device_ids = label.devices |> Enum.map(fn d -> d.id end) with {:ok, _, _} <- Labels.add_devices_to_label(device_ids, destination_label.id, current_organization), {_, nil} <- Labels.delete_devices_from_label(device_ids, label_id, current_organization) do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show_table", "graphql:label_show_table:#{label.id}:update_label_devices", %{}) ConsoleWeb.Endpoint.broadcast("graphql:label_show_table", "graphql:label_show_table:#{destination_label.id}:update_label_devices", %{}) broadcast_router_update_devices(label.devices) conn |> put_resp_header("message", "Devices have been successfully swapped to new label") |> send_resp(:no_content, "") end end defp create_label_and_apply_to_devices(devices, label_name, organization, user, conn) do current_organization = conn.assigns.current_organization cond do length(devices) == 0 -> {:error, :bad_request, "Please select a device"} Labels.get_label_by_name(String.upcase(label_name), organization.id) != nil -> {:error, :bad_request, "That label already exists"} true -> label_changeset = %Label{} |> Label.changeset(%{"name" => label_name, "organization_id" => organization.id, "creator" => user.email}) result = Ecto.Multi.new() |> Ecto.Multi.insert(:label, label_changeset) |> Ecto.Multi.run(:devices_labels, fn _repo, %{label: label} -> with {:ok, count, _} <- Labels.add_devices_to_label(devices, label.id, organization) do {:ok, {label, count}} end end) |> Repo.transaction() with {:ok, %{devices_labels: {_, count}, label: label }} <- result do ConsoleWeb.Endpoint.broadcast("graphql:labels_index_table", "graphql:labels_index_table:#{conn.assigns.current_organization.id}:label_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) device = Devices.get_device!(List.first(devices)) ConsoleWeb.Endpoint.broadcast("graphql:devices_index_table", "graphql:devices_index_table:#{current_organization.id}:device_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:device_show", "graphql:device_show:#{device.id}:device_update", %{}) broadcast_router_update_devices(label) conn |> put_resp_header("message", "#{count} Devices added to label successfully") |> send_resp(:no_content, "") end end end defp apply_label_to_devices(devices, label_id, organization, conn) do current_organization = conn.assigns.current_organization destination_label = Labels.get_label!(organization, label_id) if length(devices) == 0 do {:error, :bad_request, "Please select a device"} else with {:ok, count, devices_labels} <- Labels.add_devices_to_label(devices, destination_label.id, organization) do msg = case count do 0 -> "All selected devices are already in label" _ -> "#{count} Devices added to label successfully" end device = Devices.get_device!(List.first(devices)) ConsoleWeb.Endpoint.broadcast("graphql:label_show_table", "graphql:label_show_table:#{destination_label.id}:update_label_devices", %{}) ConsoleWeb.Endpoint.broadcast("graphql:nav_labels", "graphql:nav_labels:#{conn.assigns.current_user.id}:update_list", %{}) ConsoleWeb.Endpoint.broadcast("graphql:devices_index_table", "graphql:devices_index_table:#{current_organization.id}:device_list_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:device_show", "graphql:device_show:#{device.id}:device_update", %{}) ConsoleWeb.Endpoint.broadcast("graphql:device_show_labels_table", "graphql:device_show_labels_table:#{device.id}:device_update", %{}) assoc_devices = devices_labels |> Enum.map(fn dl -> dl.device_id end) ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => assoc_devices }) conn |> put_resp_header("message", msg) |> send_resp(:no_content, "") end end end defp broadcast_router_update_devices(%Label{} = label) do assoc_device_ids = label |> Labels.fetch_assoc([:devices]) |> Map.get(:devices) |> Enum.map(fn d -> d.id end) if length(assoc_device_ids) > 0 do ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => assoc_device_ids }) end end defp broadcast_router_update_devices(devices) do assoc_device_ids = devices |> Enum.map(fn d -> d.id end) if length(assoc_device_ids) > 0 do ConsoleWeb.Endpoint.broadcast("device:all", "device:all:refetch:devices", %{ "devices" => assoc_device_ids }) end end end
47.741228
162
0.705145
f75a30cf15da571d42d1ef943c46efb10c016f52
2,034
ex
Elixir
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_request.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_request.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_request.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataRequest do @moduledoc """ Imports data into the specified DICOM store. Returns an error if any of the files to import are not DICOM files. This API accepts duplicate DICOM instances by ignoring the newly-pushed instance. It does not overwrite. ## Attributes * `gcsSource` (*type:* `GoogleApi.HealthCare.V1beta1.Model.GoogleCloudHealthcareV1beta1DicomGcsSource.t`, *default:* `nil`) - Cloud Storage source data location and import configuration. The Cloud Healthcare Service Agent requires the `roles/storage.objectViewer` Cloud IAM roles on the Cloud Storage location. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :gcsSource => GoogleApi.HealthCare.V1beta1.Model.GoogleCloudHealthcareV1beta1DicomGcsSource.t() } field(:gcsSource, as: GoogleApi.HealthCare.V1beta1.Model.GoogleCloudHealthcareV1beta1DicomGcsSource ) end defimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataRequest do def decode(value, options) do GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.68
314
0.77237
f75a66b13f2bcb6268c834e66911001d369492e2
2,756
ex
Elixir
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/lifecycle.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/lifecycle.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/lifecycle.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudRun.V1alpha1.Model.Lifecycle do @moduledoc """ Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted. ## Attributes * `postStart` (*type:* `GoogleApi.CloudRun.V1alpha1.Model.Handler.t`, *default:* `nil`) - PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks +optional * `preStop` (*type:* `GoogleApi.CloudRun.V1alpha1.Model.Handler.t`, *default:* `nil`) - PreStop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks +optional """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :postStart => GoogleApi.CloudRun.V1alpha1.Model.Handler.t() | nil, :preStop => GoogleApi.CloudRun.V1alpha1.Model.Handler.t() | nil } field(:postStart, as: GoogleApi.CloudRun.V1alpha1.Model.Handler) field(:preStop, as: GoogleApi.CloudRun.V1alpha1.Model.Handler) end defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.Lifecycle do def decode(value, options) do GoogleApi.CloudRun.V1alpha1.Model.Lifecycle.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.Lifecycle do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.12
525
0.771771
f75a67a021e53c3561036000a1886cae030819b7
3,375
ex
Elixir
lib/vutuv_web/controllers/work_experience_controller.ex
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
309
2016-05-03T17:16:23.000Z
2022-03-01T09:30:22.000Z
lib/vutuv_web/controllers/work_experience_controller.ex
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
662
2016-04-27T07:45:18.000Z
2022-01-05T07:29:19.000Z
lib/vutuv_web/controllers/work_experience_controller.ex
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
40
2016-04-27T07:46:22.000Z
2021-12-31T05:54:34.000Z
defmodule VutuvWeb.WorkExperienceController do use VutuvWeb, :controller import VutuvWeb.Authorize alias Vutuv.{Biographies, Biographies.WorkExperience, UserProfiles, UserProfiles.User} @dialyzer {:nowarn_function, new: 3} def action(conn, _), do: auth_action_slug(conn, __MODULE__, [:index, :show]) def index(conn, %{"user_slug" => slug}, %User{slug: slug} = current_user) do work_experiences = Biographies.list_work_experiences(current_user) render(conn, "index.html", work_experiences: work_experiences, user: current_user) end def index(conn, %{"user_slug" => slug}, _current_user) do user = UserProfiles.get_user!(%{"slug" => slug}) work_experiences = Biographies.list_work_experiences(user) render(conn, "index.html", work_experiences: work_experiences, user: user) end def new(conn, _params, _current_user) do changeset = Biographies.change_work_experience(%WorkExperience{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"work_experience" => work_experience_params}, current_user) do case Biographies.create_work_experience(current_user, work_experience_params) do {:ok, work_experience} -> conn |> put_flash(:info, gettext("Work experience created successfully.")) |> redirect( to: Routes.user_work_experience_path(conn, :show, current_user, work_experience) ) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, %{"id" => id, "user_slug" => slug}, %User{slug: slug} = current_user) do work_experience = Biographies.get_work_experience!(current_user, id) render(conn, "show.html", work_experience: work_experience, user: current_user) end def show(conn, %{"id" => id, "user_slug" => slug}, _current_user) do user = UserProfiles.get_user!(%{"slug" => slug}) work_experience = Biographies.get_work_experience!(user, id) render(conn, "show.html", work_experience: work_experience, user: user) end def edit(conn, %{"id" => id}, current_user) do work_experience = Biographies.get_work_experience!(current_user, id) changeset = Biographies.change_work_experience(work_experience) render(conn, "edit.html", work_experience: work_experience, changeset: changeset) end def update(conn, %{"id" => id, "work_experience" => work_experience_params}, current_user) do work_experience = Biographies.get_work_experience!(current_user, id) case Biographies.update_work_experience(work_experience, work_experience_params) do {:ok, work_experience} -> conn |> put_flash(:info, gettext("Work experience updated successfully.")) |> redirect( to: Routes.user_work_experience_path(conn, :show, current_user, work_experience) ) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", work_experience: work_experience, changeset: changeset) end end def delete(conn, %{"id" => id}, current_user) do work_experience = Biographies.get_work_experience!(current_user, id) {:ok, _work_experience} = Biographies.delete_work_experience(work_experience) conn |> put_flash(:info, gettext("Work experience deleted successfully.")) |> redirect(to: Routes.user_work_experience_path(conn, :index, current_user)) end end
40.178571
95
0.712
f75a8f98006ea33db78e1fe2e3bf37fed818054e
2,137
exs
Elixir
youtube/elixir_casts/chat/test/chat/chats_test.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
null
null
null
youtube/elixir_casts/chat/test/chat/chats_test.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
1
2021-03-28T13:57:15.000Z
2021-03-29T12:42:21.000Z
youtube/elixir_casts/chat/test/chat/chats_test.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
null
null
null
defmodule Chat.ChatsTest do use Chat.DataCase alias Chat.Chats describe "messages" do alias Chat.Chats.Message @valid_attrs %{body: "some body", name: "some name"} @update_attrs %{body: "some updated body", name: "some updated name"} @invalid_attrs %{body: nil, name: nil} def message_fixture(attrs \\ %{}) do {:ok, message} = attrs |> Enum.into(@valid_attrs) |> Chats.create_message() message end test "list_messages/0 returns all messages" do message = message_fixture() assert Chats.list_messages() == [message] end test "get_message!/1 returns the message with given id" do message = message_fixture() assert Chats.get_message!(message.id) == message end test "create_message/1 with valid data creates a message" do assert {:ok, %Message{} = message} = Chats.create_message(@valid_attrs) assert message.body == "some body" assert message.name == "some name" end test "create_message/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Chats.create_message(@invalid_attrs) end test "update_message/2 with valid data updates the message" do message = message_fixture() assert {:ok, %Message{} = message} = Chats.update_message(message, @update_attrs) assert message.body == "some updated body" assert message.name == "some updated name" end test "update_message/2 with invalid data returns error changeset" do message = message_fixture() assert {:error, %Ecto.Changeset{}} = Chats.update_message(message, @invalid_attrs) assert message == Chats.get_message!(message.id) end test "delete_message/1 deletes the message" do message = message_fixture() assert {:ok, %Message{}} = Chats.delete_message(message) assert_raise Ecto.NoResultsError, fn -> Chats.get_message!(message.id) end end test "change_message/1 returns a message changeset" do message = message_fixture() assert %Ecto.Changeset{} = Chats.change_message(message) end end end
31.895522
88
0.670098
f75a93ece3aa1857e89eb0e0c6753387ed836257
89
exs
Elixir
test/views/layout_view_test.exs
skatsuta/phoenix-json-api
1da16fc10cf1ce7bb5e47034755f5990bd7acb92
[ "MIT" ]
null
null
null
test/views/layout_view_test.exs
skatsuta/phoenix-json-api
1da16fc10cf1ce7bb5e47034755f5990bd7acb92
[ "MIT" ]
null
null
null
test/views/layout_view_test.exs
skatsuta/phoenix-json-api
1da16fc10cf1ce7bb5e47034755f5990bd7acb92
[ "MIT" ]
null
null
null
defmodule PhoenixJsonApi.LayoutViewTest do use PhoenixJsonApi.ConnCase, async: true end
29.666667
42
0.853933
f75acb37b47a0bf0ff5b40c721b7fa88290d870a
546
ex
Elixir
examples/ecto_poll_queue/lib/ecto_poll_queue_example/classify_photo.ex
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
717
2015-06-15T19:30:54.000Z
2022-03-22T06:10:09.000Z
examples/ecto_poll_queue/lib/ecto_poll_queue_example/classify_photo.ex
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
106
2015-06-25T05:38:05.000Z
2021-12-08T23:17:19.000Z
examples/ecto_poll_queue/lib/ecto_poll_queue_example/classify_photo.ex
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
60
2015-06-07T00:48:37.000Z
2022-03-06T08:20:23.000Z
defmodule EctoPollQueueExample.ClassifyPhoto do alias EctoPollQueueExample.Photo alias EctoPollQueueExample.Repo def run(id) do photo = Repo.get(Photo, id) if photo.sleep do Process.sleep(photo.sleep) end if photo.from do send(photo.from, {:classify_job_ran, id}) end if photo.should_fail do raise "classifier's totally busted dude!" end tag = Enum.random(["newt", "ripley", "jonesey", "xenomorph"]) photo |> Ecto.Changeset.change(%{tag: tag}) |> Repo.update!() end end
20.222222
65
0.657509
f75af09de4a38d72274c3459f29104fa0191605a
1,906
exs
Elixir
rel/config.exs
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
6
2017-08-10T13:57:06.000Z
2019-01-17T08:48:40.000Z
rel/config.exs
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
14
2017-08-08T13:07:00.000Z
2019-02-28T15:10:18.000Z
rel/config.exs
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
null
null
null
# Import all plugins from `rel/plugins` # They can then be used by adding `plugin MyPlugin` to # either an environment, or release definition, where # `MyPlugin` is the name of the plugin module. ~w(rel plugins *.exs) |> Path.join() |> Path.wildcard() |> Enum.map(&Code.eval_file(&1)) use Mix.Releases.Config, # This sets the default release built by `mix release` default_release: :default, # This sets the default environment used by `mix release` default_environment: Mix.env() # For a full list of config options for both releases # and environments, visit https://hexdocs.pm/distillery/config/distillery.html # You may define one or more environments in this file, # an environment's settings will override those of a release # when building in that environment, this combination of release # and environment configuration is called a profile environment :dev do # If you are running Phoenix, you should make sure that # server: true is set and the code reloader is disabled, # even in dev mode. # It is recommended that you build with MIX_ENV=prod and pass # the --env flag to Distillery explicitly if you want to use # dev mode. set(dev_mode: true) set(include_erts: false) set(cookie: :"<s:^I@zETCESKo$B&)J~z>0%Jz=LVi;P{`s=(8wE%4LyZ4c0CdYMB9{pNuQtuM_@") end environment :prod do set(include_erts: true) set(include_src: false) set(cookie: :"py/R/_/Z7?x5`(F.bRG%WM1=5<&Ml6bOZc<9FGT}mPXah4B<F$<1A8~Wq/IjXZK>") set(vm_args: "rel/vm.args") end # You may define one or more releases in this file. # If you have not set a default release, or selected one # when running `mix release`, the first release in the file # will be used by default release :discord_splatoon_bot do set(version: "0.1.0") set( applications: [ :runtime_tools, discord_splatoon_bot: :permanent, spla2_api: :permanent, splatoon_data: :permanent ] ) end
31.766667
82
0.723505
f75b3d317f574ec9dd04618ff59d78fde0ba782e
200
ex
Elixir
lib/mail_in_a_box/miab_imap.ex
ourway/mail_in_a_box
6c0123fb842dcd98dee970ad5501f2a18afd5a91
[ "MIT" ]
null
null
null
lib/mail_in_a_box/miab_imap.ex
ourway/mail_in_a_box
6c0123fb842dcd98dee970ad5501f2a18afd5a91
[ "MIT" ]
null
null
null
lib/mail_in_a_box/miab_imap.ex
ourway/mail_in_a_box
6c0123fb842dcd98dee970ad5501f2a18afd5a91
[ "MIT" ]
null
null
null
defmodule MIAB.IMAP do @moduledoc false @settings Application.get_env(:mail_in_a_box, __MODULE__) for {_k, _v} <- @settings do :pass # :ok = Application.put_env(:eximap, k, v) end end
22.222222
59
0.685
f75b4812edf6fe3c1d43eaedc6eadd0d46ebbaef
218
ex
Elixir
lib/team_budget_graphql/resolvers/types.ex
AkioCode/elxpro4-teambudget
a7e67d5e1ec538df6cc369cc4f385d005bf60eda
[ "MIT" ]
null
null
null
lib/team_budget_graphql/resolvers/types.ex
AkioCode/elxpro4-teambudget
a7e67d5e1ec538df6cc369cc4f385d005bf60eda
[ "MIT" ]
null
null
null
lib/team_budget_graphql/resolvers/types.ex
AkioCode/elxpro4-teambudget
a7e67d5e1ec538df6cc369cc4f385d005bf60eda
[ "MIT" ]
null
null
null
defmodule TeamBudgetGraphql.Types do use Absinthe.Schema.Notation alias TeamBudgetGraphql.Types import_types(Types.Session) import_types(Types.User) import_types(Types.Team) import_types(Types.Invite) end
21.8
36
0.811927
f75b7d815fe5ae5c3e3df54755eafae6385942ba
906
ex
Elixir
lib/asn.ex
ephe-meral/asn
4772d1c44a85acd9e110a866d8f7561fedf07fc4
[ "WTFPL" ]
12
2016-07-06T11:29:31.000Z
2022-03-11T01:01:41.000Z
lib/asn.ex
ephe-meral/asn
4772d1c44a85acd9e110a866d8f7561fedf07fc4
[ "WTFPL" ]
null
null
null
lib/asn.ex
ephe-meral/asn
4772d1c44a85acd9e110a866d8f7561fedf07fc4
[ "WTFPL" ]
2
2017-03-19T03:24:47.000Z
2019-11-12T14:12:14.000Z
defmodule ASN do use Application def start(_type, _args) do import Supervisor.Spec, warn: false children = [ worker(ASN.Matcher, [[name: __MODULE__]]) ] opts = [strategy: :one_for_one, name: ASN.Supervisor] Supervisor.start_link(children, opts) end @doc """ Returns the associated AS-Name of the given IP if any. """ @spec ip_to_asn(String.t | :inet.ip4_address) :: {:ok, String.t} | :error def ip_to_asn(ip), do: ASN.Matcher.ip_to_asn(__MODULE__, ip) @doc """ Returns the associated AS-ID of the given IP if any. """ @spec ip_to_as(String.t | :inet.ip4_address) :: {:ok, integer} | :error def ip_to_as(ip), do: ASN.Matcher.ip_to_as(__MODULE__, ip) @doc """ Returns the associated AS-Name of the given AS-ID if any. """ @spec as_to_asn(integer) :: {:ok, String.t} | :error def as_to_asn(as), do: ASN.Matcher.as_to_asn(__MODULE__, as) end
27.454545
75
0.663355
f75b7e8b38e9051560d257127d3dd4c1f4bd9a64
1,003
exs
Elixir
03-input-output.exs
yortz/30-days-of-elixir
b7126eeee16b726df0b00234fd4aff03a5c3e1a9
[ "MIT" ]
null
null
null
03-input-output.exs
yortz/30-days-of-elixir
b7126eeee16b726df0b00234fd4aff03a5c3e1a9
[ "MIT" ]
null
null
null
03-input-output.exs
yortz/30-days-of-elixir
b7126eeee16b726df0b00234fd4aff03a5c3e1a9
[ "MIT" ]
null
null
null
# http://elixir-lang.org/docs/stable/IO.html # http://elixir-lang.org/docs/stable/File.html defmodule CowInterrogator do def get_name do String.strip IO.gets("What is your name? ") end def get_cow_lover do IO.getn("Do you like cows? ", 1) end def interrogate do name = get_name case String.downcase(get_cow_lover) do "y" -> IO.puts "Great! Here's a cow for you #{name}:" IO.puts cow_art "n" -> IO.puts "That's a shame, #{name}." _ -> IO.puts "You should have entered 'Y' or 'N'." end end def cow_art do path = Path.expand("support/cow.txt", __DIR__) case File.read(path) do {:ok, art} -> art {:error, _} -> IO.puts "Error: cow.txt file not found"; System.halt(1) end end end ExUnit.start defmodule InputOutputTest do use ExUnit.Case import String test "read file" do art = CowInterrogator.cow_art assert strip(art) |> first == "(" end end CowInterrogator.interrogate
20.06
76
0.623131
f75ba736b6e0d448d5b4655646282e5db3704920
25,408
exs
Elixir
test/remote_ip/headers/forwarded_test.exs
devstopfix/remote_ip
c52084369a0da2f7700679b35085dca0eed5ff0d
[ "MIT" ]
null
null
null
test/remote_ip/headers/forwarded_test.exs
devstopfix/remote_ip
c52084369a0da2f7700679b35085dca0eed5ff0d
[ "MIT" ]
null
null
null
test/remote_ip/headers/forwarded_test.exs
devstopfix/remote_ip
c52084369a0da2f7700679b35085dca0eed5ff0d
[ "MIT" ]
null
null
null
defmodule RemoteIp.Headers.ForwardedTest do use ExUnit.Case, async: true alias RemoteIp.Headers.Forwarded doctest Forwarded describe "parsing" do test "RFC 7239 examples" do parsed = Forwarded.parse(~S'for="_gazonk"') assert parsed == [] parsed = Forwarded.parse(~S'For="[2001:db8:cafe::17]:4711"') assert parsed == [{8193, 3512, 51966, 0, 0, 0, 0, 23}] parsed = Forwarded.parse(~S'for=192.0.2.60;proto=http;by=203.0.113.43') assert parsed == [{192, 0, 2, 60}] parsed = Forwarded.parse(~S'for=192.0.2.43, for=198.51.100.17') assert parsed == [{192, 0, 2, 43}, {198, 51, 100, 17}] end test "case insensitivity" do assert [{0, 0, 0, 0}] == Forwarded.parse(~S'for=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'foR=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'fOr=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'fOR=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'For=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'FoR=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'FOr=0.0.0.0') assert [{0, 0, 0, 0}] == Forwarded.parse(~S'FOR=0.0.0.0') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'for="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'foR="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'fOr="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'fOR="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'For="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'FoR="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'FOr="[::]"') assert [{0, 0, 0, 0, 0, 0, 0, 0}] == Forwarded.parse(~S'FOR="[::]"') end test "IPv4" do assert [] == Forwarded.parse(~S'for=') assert [] == Forwarded.parse(~S'for=1') assert [] == Forwarded.parse(~S'for=1.2') assert [] == Forwarded.parse(~S'for=1.2.3') assert [] == Forwarded.parse(~S'for=1000.2.3.4') assert [] == Forwarded.parse(~S'for=1.2000.3.4') assert [] == Forwarded.parse(~S'for=1.2.3000.4') assert [] == Forwarded.parse(~S'for=1.2.3.4000') assert [] == Forwarded.parse(~S'for=1abc.2.3.4') assert [] == Forwarded.parse(~S'for=1.2abc.3.4') assert [] == Forwarded.parse(~S'for=1.2.3.4abc') assert [] == Forwarded.parse(~S'for=1.2.3abc.4') assert [] == Forwarded.parse(~S'for=1.2.3.4abc') assert [] == Forwarded.parse(~S'for="1.2.3.4') assert [] == Forwarded.parse(~S'for=1.2.3.4"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for=1.2.3.4') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="\1.2\.3.\4"') end test "IPv4 with port" do assert [] == Forwarded.parse(~S'for=1.2.3.4:') assert [] == Forwarded.parse(~S'for=1.2.3.4:1') assert [] == Forwarded.parse(~S'for=1.2.3.4:12') assert [] == Forwarded.parse(~S'for=1.2.3.4:123') assert [] == Forwarded.parse(~S'for=1.2.3.4:1234') assert [] == Forwarded.parse(~S'for=1.2.3.4:12345') assert [] == Forwarded.parse(~S'for=1.2.3.4:123456') assert [] == Forwarded.parse(~S'for=1.2.3.4:_underscore') assert [] == Forwarded.parse(~S'for=1.2.3.4:no_underscore') assert [] == Forwarded.parse(~S'for="1.2.3.4:"') assert [] == Forwarded.parse(~S'for="1.2.3.4:123456"') assert [] == Forwarded.parse(~S'for="1.2.3.4:no_underscore"') assert [] == Forwarded.parse(~S'for="1.2\.3.4\:no_un\der\score"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:1"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:12"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:123"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:1234"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:12345"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="1.2.3.4:_underscore"') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for="\1.2\.3.4\:_po\r\t"') end test "improperly formatted IPv6" do assert [] == Forwarded.parse(~S'for=[127.0.0.1]') assert [] == Forwarded.parse(~S'for="[127.0.0.1]"') assert [] == Forwarded.parse(~S'for=::127.0.0.1') assert [] == Forwarded.parse(~S'for=[::127.0.0.1]') assert [] == Forwarded.parse(~S'for="::127.0.0.1"') assert [] == Forwarded.parse(~S'for="[::127.0.0.1"') assert [] == Forwarded.parse(~S'for="::127.0.0.1]"') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8"') assert [] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8]"') end test "IPv6 with port" do assert [] == Forwarded.parse(~S'for=::1.2.3.4:') assert [] == Forwarded.parse(~S'for=::1.2.3.4:1') assert [] == Forwarded.parse(~S'for=::1.2.3.4:12') assert [] == Forwarded.parse(~S'for=::1.2.3.4:123') assert [] == Forwarded.parse(~S'for=::1.2.3.4:1234') assert [] == Forwarded.parse(~S'for=::1.2.3.4:12345') assert [] == Forwarded.parse(~S'for=::1.2.3.4:123456') assert [] == Forwarded.parse(~S'for=::1.2.3.4:_underscore') assert [] == Forwarded.parse(~S'for=::1.2.3.4:no_underscore') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:1') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:12') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:123') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:1234') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:12345') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:123456') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:_underscore') assert [] == Forwarded.parse(~S'for=[::1.2.3.4]:no_underscore') assert [] == Forwarded.parse(~S'for="::1.2.3.4:"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:123456"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:no_underscore"') assert [] == Forwarded.parse(~S'for="::1.2\.3.4\:no_un\der\score"') assert [] == Forwarded.parse(~S'for="[::1.2.3.4]:"') assert [] == Forwarded.parse(~S'for="[::1.2.3.4]:123456"') assert [] == Forwarded.parse(~S'for="[::1.2.3.4]:no_underscore"') assert [] == Forwarded.parse(~S'for="\[::1.2\.3.4]\:no_un\der\score"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:1"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:12"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:123"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:1234"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:12345"') assert [] == Forwarded.parse(~S'for="::1.2.3.4:_underscore"') assert [] == Forwarded.parse(~S'for="::\1.2\.3.4\:_po\r\t"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:1"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:12"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:123"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:1234"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:12345"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::1.2.3.4]:_underscore"') assert [{0, 0, 0, 0, 0, 0, 258, 772}] == Forwarded.parse(~S'for="[::\1.2\.3.4\]\:_po\r\t"') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:1') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:12') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:123') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:1234') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:12345') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:123456') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:_underscore') assert [] == Forwarded.parse(~S'for=1:2:3:4:5:6:7:8:no_underscore') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:1') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:12') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:123') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:1234') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:12345') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:123456') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:_underscore') assert [] == Forwarded.parse(~S'for=[1:2:3:4:5:6:7:8]:no_underscore') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:123456"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:no_underscore"') assert [] == Forwarded.parse(~S'for="::1.2\.3.4\:no_un\der\score"') assert [] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:"') assert [] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:123456"') assert [] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:no_underscore"') assert [] == Forwarded.parse(~S'for="\[1:2\:3:4:5:6:7:8]\:no_un\der\score"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:1"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:12"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:123"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:1234"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:12345"') assert [] == Forwarded.parse(~S'for="1:2:3:4:5:6:7:8:_underscore"') assert [] == Forwarded.parse(~S'for="\1:2\:3:4:5:6:7:8\:_po\r\t"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:1"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:12"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:123"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:1234"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:12345"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:5:6:7:8]:_underscore"') assert [{1, 2, 3, 4, 5, 6, 7, 8}] == Forwarded.parse(~S'for="[1:2:3:4:\5:6\:7:8\]\:_po\r\t"') end test "IPv6 without ::" do assert [{0x0001, 0x0023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890:a:bc:def:d34d]"') assert [{0x0001, 0x0023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456:7890:a:bc:1.2.3.4]"') end test "IPv6 with :: at position 0" do assert [{0x0000, 0x0023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::23:456:7890:a:bc:def:d34d]"') assert [{0x0000, 0x0023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::23:456:7890:a:bc:1.2.3.4]"') assert [{0x0000, 0x0000, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::456:7890:a:bc:def:d34d]"') assert [{0x0000, 0x0000, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::456:7890:a:bc:1.2.3.4]"') assert [{0x0000, 0x0000, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::7890:a:bc:def:d34d]"') assert [{0x0000, 0x0000, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::7890:a:bc:1.2.3.4]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::a:bc:def:d34d]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::a:bc:1.2.3.4]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::bc:def:d34d]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::bc:1.2.3.4]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[::def:d34d]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[::1.2.3.4]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[::d34d]"') assert [{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[::]"') end test "IPv6 with :: at position 1" do assert [{0x0001, 0x000, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1::456:7890:a:bc:def:d34d]"') assert [{0x0001, 0x000, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1::456:7890:a:bc:1.2.3.4]"') assert [{0x0001, 0x000, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1::7890:a:bc:def:d34d]"') assert [{0x0001, 0x000, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1::7890:a:bc:1.2.3.4]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1::a:bc:def:d34d]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1::a:bc:1.2.3.4]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1::bc:def:d34d]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1::bc:1.2.3.4]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1::def:d34d]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1::1.2.3.4]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1::d34d]"') assert [{0x0001, 0x000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1::]"') end test "IPv6 with :: at position 2" do assert [{0x0001, 0x023, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23::7890:a:bc:def:d34d]"') assert [{0x0001, 0x023, 0x0000, 0x7890, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23::7890:a:bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23::a:bc:def:d34d]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23::a:bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23::bc:def:d34d]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23::bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23::def:d34d]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23::1.2.3.4]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1:23::d34d]"') assert [{0x0001, 0x023, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1:23::]"') end test "IPv6 with :: at position 3" do assert [{0x0001, 0x023, 0x0456, 0x0000, 0x000A, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456::a:bc:def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x000A, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456::a:bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456::bc:def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456::bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456::def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456::1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456::d34d]"') assert [{0x0001, 0x023, 0x0456, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1:23:456::]"') end test "IPv6 with :: at position 4" do assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x00BC, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890::bc:def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x00BC, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456:7890::bc:1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890::def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456:7890::1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890::d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1:23:456:7890::]"') end test "IPv6 with :: at position 5" do assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x0000, 0x0DEF, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890:a::def:d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x0000, 0x0102, 0x0304}] == Forwarded.parse(~S'for="[1:23:456:7890:a::1.2.3.4]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x0000, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890:a::d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1:23:456:7890:a::]"') end test "IPv6 with :: at position 6" do assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0000, 0xD34D}] == Forwarded.parse(~S'for="[1:23:456:7890:a:bc::d34d]"') assert [{0x0001, 0x023, 0x0456, 0x7890, 0x000A, 0x00BC, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[1:23:456:7890:a:bc::]"') end test "IPv6 with leading zeroes" do assert [{0x0000, 0x0001, 0x0002, 0x0003, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[0:01:002:0003:0000::]"') assert [{0x000A, 0x001A, 0x002A, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[0a:01a:002a::]"') assert [{0x00AB, 0x01AB, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[0ab:01ab::]"') assert [{0x0ABC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}] == Forwarded.parse(~S'for="[0abc::]"') end test "IPv6 with mixed case" do assert [{0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD}] == Forwarded.parse(~S'for="[abcd:abcD:abCd:abCD:aBcd:aBcD:aBCd:aBCD]"') assert [{0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD, 0xABCD}] == Forwarded.parse(~S'for="[Abcd:AbcD:AbCd:AbCD:ABcd:ABcD:ABCd:ABCD]"') end test "semicolons" do assert [{1, 2, 3, 4}] == Forwarded.parse(~S'for=1.2.3.4;proto=http;by=2.3.4.5') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'proto=http;for=1.2.3.4;by=2.3.4.5') assert [{1, 2, 3, 4}] == Forwarded.parse(~S'proto=http;by=2.3.4.5;for=1.2.3.4') assert [] == Forwarded.parse(~S'for=1.2.3.4proto=http;by=2.3.4.5') assert [] == Forwarded.parse(~S'proto=httpfor=1.2.3.4;by=2.3.4.5') assert [] == Forwarded.parse(~S'proto=http;by=2.3.4.5for=1.2.3.4') assert [] == Forwarded.parse(~S'for=1.2.3.4;proto=http;by=2.3.4.5;') assert [] == Forwarded.parse(~S'proto=http;for=1.2.3.4;by=2.3.4.5;') assert [] == Forwarded.parse(~S'proto=http;by=2.3.4.5;for=1.2.3.4;') assert [] == Forwarded.parse(~S'for=1.2.3.4;proto=http;for=2.3.4.5') assert [] == Forwarded.parse(~S'for=1.2.3.4;for=2.3.4.5;proto=http') assert [] == Forwarded.parse(~S'proto=http;for=1.2.3.4;for=2.3.4.5') end test "parameters other than `for`" do assert [] == Forwarded.parse(~S'by=1.2.3.4') assert [] == Forwarded.parse(~S'host=example.com') assert [] == Forwarded.parse(~S'proto=http') assert [] == Forwarded.parse(~S'by=1.2.3.4;proto=http;host=example.com') end test "bad whitespace" do assert [] == Forwarded.parse(~S'for= 1.2.3.4') assert [] == Forwarded.parse(~S'for = 1.2.3.4') assert [] == Forwarded.parse(~S'for=1.2.3.4; proto=http') assert [] == Forwarded.parse(~S'for=1.2.3.4 ;proto=http') assert [] == Forwarded.parse(~S'for=1.2.3.4 ; proto=http') assert [] == Forwarded.parse(~S'proto=http; for=1.2.3.4') assert [] == Forwarded.parse(~S'proto=http ;for=1.2.3.4') assert [] == Forwarded.parse(~S'proto=http ; for=1.2.3.4') end test "commas" do assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse(~S'for=1.2.3.4, for=2.3.4.5') assert [{1, 2, 3, 4}, {0, 0, 0, 0, 2, 3, 4, 5}] == Forwarded.parse(~S'for=1.2.3.4, for="[::2:3:4:5]"') assert [{1, 2, 3, 4}, {0, 0, 0, 0, 2, 3, 4, 5}] == Forwarded.parse(~S'for=1.2.3.4, for="[::2:3:4:5]"') assert [{0, 0, 0, 0, 1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse(~S'for="[::1:2:3:4]", for=2.3.4.5') assert [{0, 0, 0, 0, 1, 2, 3, 4}, {0, 0, 0, 0, 2, 3, 4, 5}] == Forwarded.parse(~S'for="[::1:2:3:4]", for="[::2:3:4:5]"') end test "optional whitespace" do assert [{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}, {5, 6, 7, 8}] == Forwarded.parse( "for=1.2.3.4,for=2.3.4.5,\sfor=3.4.5.6\s,for=4.5.6.7\s,\sfor=5.6.7.8" ) assert [{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}, {5, 6, 7, 8}] == Forwarded.parse( "for=1.2.3.4,for=2.3.4.5,\tfor=3.4.5.6\t,for=4.5.6.7\t,\tfor=5.6.7.8" ) assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\s,\s\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\s,\s\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\s,\t\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\s,\t\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\t,\s\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\t,\s\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\t,\t\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\s\t,\t\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\s,\s\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\s,\s\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\s,\t\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\s,\t\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\t,\s\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\t,\s\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\t,\t\sfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\t,\t\tfor=2.3.4.5") assert [{1, 2, 3, 4}, {2, 3, 4, 5}] == Forwarded.parse("for=1.2.3.4\t\s\s\s\s\t\s\t\s\t,\t\s\s\t\tfor=2.3.4.5") end test "commas and semicolons" do assert [{1, 2, 3, 4}, {0, 0, 0, 0, 2, 3, 4, 5}, {3, 4, 5, 6}, {0, 0, 0, 0, 4, 5, 6, 7}] == Forwarded.parse( ~S'for=1.2.3.4, for="[::2:3:4:5]";proto=http;host=example.com, proto=http;for=3.4.5.6;by=127.0.0.1, proto=http;host=example.com;for="[::4:5:6:7]"' ) end end end
50.412698
163
0.536052
f75bcb658e85b3db9753b13ae7f9691abad53a2e
267
ex
Elixir
lib/brook/legacy.ex
bbalser/brook
b628605efd753a7c1cfe26bf3c4e4dc6fab4709b
[ "Apache-2.0" ]
14
2019-08-15T05:44:24.000Z
2020-05-28T23:13:59.000Z
lib/brook/legacy.ex
bbalser/brook
b628605efd753a7c1cfe26bf3c4e4dc6fab4709b
[ "Apache-2.0" ]
2
2019-08-24T20:11:28.000Z
2019-09-23T20:35:42.000Z
lib/brook/legacy.ex
bbalser/brook
b628605efd753a7c1cfe26bf3c4e4dc6fab4709b
[ "Apache-2.0" ]
3
2019-08-13T15:23:32.000Z
2020-02-19T19:46:10.000Z
defmodule Brook.Legacy do defdelegate serialize(term), to: JsonSerde def deserialize(string) do case String.contains?(string, "__brook_struct__") do true -> Brook.Serde.deserialize(string) false -> JsonSerde.deserialize(string) end end end
24.272727
56
0.719101
f75be17f7c81baa3d20393ba2d9c14d117cbb39b
1,108
ex
Elixir
lib/mango_pay/event.ex
Eweev/mangopay-elixir
7a4ff7b47c31bfa9a77d944803158f8297d51505
[ "MIT" ]
1
2020-04-07T22:17:25.000Z
2020-04-07T22:17:25.000Z
lib/mango_pay/event.ex
Eweev/mangopay-elixir
7a4ff7b47c31bfa9a77d944803158f8297d51505
[ "MIT" ]
17
2018-04-11T12:07:07.000Z
2019-03-18T21:33:18.000Z
lib/mango_pay/event.ex
Eweev/mangopay-elixir
7a4ff7b47c31bfa9a77d944803158f8297d51505
[ "MIT" ]
2
2018-05-15T12:41:46.000Z
2019-04-08T14:19:15.000Z
defmodule MangoPay.Event do @moduledoc """ Functions for MangoPay [event](https://docs.mangopay.com/endpoints/v2.01/events#e251_the-event-object). """ use MangoPay.Query.Base set_path "events" @doc """ List all disputes. ## Examples query = %{ "Page": 1, "Per_Page": 25, "Sort": "CreationDate:DESC", "BeforeDate": 1463440221, "AfterDate": 1431817821, "EventType": "PAYIN_NORMAL_CREATED" } {:ok, events} = MangoPay.Event.all(query) """ def all(query \\ %{}) do _all(nil, query) end @doc """ List all disputes. ## Examples query = %{ "Page": 1, "Per_Page": 25, "Sort": "CreationDate:DESC", "BeforeDate": 1463440221, "AfterDate": 1431817821, "EventType": "PAYIN_NORMAL_CREATED" } events = MangoPay.Event.all!(query) """ def all!(query \\ %{}) do _all!(nil, query) end end
24.086957
105
0.481047
f75befc5cdc4396313e20167dc71e1e52f27d2c8
2,319
ex
Elixir
verify/geolix/lib/mix/tasks/geolix/verify.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
verify/geolix/lib/mix/tasks/geolix/verify.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
verify/geolix/lib/mix/tasks/geolix/verify.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Geolix.Verify do @moduledoc """ Verifies Geolix results. """ alias Geolix.Database.Loader use Mix.Task @shortdoc "Verifies parser results" @data_path Path.expand("../../../../..", __DIR__) @ip_set Path.join(@data_path, "ip_set.txt") @results Path.join(@data_path, "geolix_results.txt") def run(_args) do {:ok, _} = Application.ensure_all_started(:geolix) :ok = wait_for_database_loader() result_file = @results |> File.open!([:write, :utf8]) @ip_set |> File.read!() |> String.split() |> check(result_file) end defp check([], _), do: :ok defp check([ip | ips], result_file) do {asn_data, city_data, country_data} = ip |> Geolix.lookup() |> parse() IO.puts(result_file, "#{ip}-#{asn_data}-#{city_data}-#{country_data}") check(ips, result_file) end defp parse(%{asn: asn, city: city, country: country}) do {parse_asn(asn), parse_city(city), parse_country(country)} end defp parse_asn(%{autonomous_system_number: num}), do: num defp parse_asn(_), do: "" defp parse_city(%{location: location, city: city}) do [ city_latitude(location), city_longitude(location), city_name(city) ] |> Enum.join("_") end defp parse_city(_), do: "" defp city_latitude(%{latitude: latitude}), do: latitude defp city_latitude(nil), do: "None" defp city_longitude(%{longitude: longitude}), do: longitude defp city_longitude(nil), do: "None" defp city_name(%{names: names}), do: names.en defp city_name(%{}), do: "" defp city_name(city), do: city defp parse_country(%{country: %{names: names}}), do: names.en defp parse_country(%{country: %{}}), do: "" defp parse_country(%{country: country}), do: country defp parse_country(_), do: "" defp wait_for_database_loader, do: wait_for_database_loader(30_000) defp wait_for_database_loader(0) do IO.puts("Loading databases took longer than 30 seconds. Aborting...") :error end defp wait_for_database_loader(timeout) do delay = 250 loaded = Loader.loaded_databases() registered = Loader.registered_databases() if 0 < length(registered) && loaded == registered do :ok else :timer.sleep(delay) wait_for_database_loader(timeout - delay) end end end
24.670213
74
0.655024
f75c112beb2f631e887efc8c380ade5d4dedcb9e
700
ex
Elixir
lib/genstage_importer/parser.ex
kloeckner-i/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
4
2019-07-27T13:11:54.000Z
2020-06-19T14:00:21.000Z
lib/genstage_importer/parser.ex
altmer/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
null
null
null
lib/genstage_importer/parser.ex
altmer/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
2
2018-08-02T11:01:15.000Z
2019-11-15T12:35:40.000Z
defmodule GenstageImporter.Parser do @moduledoc """ Contains functions to parse some raw data from CSV files """ require Logger def parse_decimal(decimal_string) do case Decimal.parse(decimal_string) do :error -> Logger.debug(fn -> "[GenstageImporter] bad decimal value: [#{decimal_string}]" end) Decimal.new(0) {:ok, decimal} -> decimal end end def parse_integer(integer_string) do case Integer.parse(integer_string) do :error -> Logger.debug(fn -> "[GenstageImporter] bad integer value: [#{integer_string}]" end) 0 {integer, _} -> integer end end end
19.444444
69
0.6
f75c2ecac8f0e5ced192eb4e6a9a977b8df9bdb2
2,850
exs
Elixir
mix.exs
verypossible/nerves_system_onlogic_cl210
cb220ae352d9e14af7efa1f4bfb989bdfed69f04
[ "Apache-2.0" ]
8
2020-01-08T18:01:06.000Z
2020-02-13T04:43:30.000Z
mix.exs
verypossible/nerves_system_onlogic_cl210
cb220ae352d9e14af7efa1f4bfb989bdfed69f04
[ "Apache-2.0" ]
1
2020-03-17T17:54:41.000Z
2020-03-17T17:54:41.000Z
mix.exs
verypossible/nerves_system_onlogic_cl210
cb220ae352d9e14af7efa1f4bfb989bdfed69f04
[ "Apache-2.0" ]
2
2020-01-29T18:08:42.000Z
2021-01-06T15:20:05.000Z
defmodule NervesSystemOnLogicCL210.MixProject do use Mix.Project @github_organization "verypossible" @app :nerves_system_onlogic_cl210 @version Path.join(__DIR__, "VERSION") |> File.read!() |> String.trim() def project do [ app: @app, version: @version, elixir: "~> 1.6", compilers: Mix.compilers() ++ [:nerves_package], nerves_package: nerves_package(), description: description(), package: package(), deps: deps(), aliases: [loadconfig: [&bootstrap/1]], docs: [extras: ["README.md"], main: "readme"] ] end def application do [] end defp bootstrap(args) do set_target() Application.start(:nerves_bootstrap) Mix.Task.run("loadconfig", args) end defp nerves_package do [ type: :system, artifact_sites: [ {:github_releases, "#{@github_organization}/#{@app}"} ], build_runner_opts: build_runner_opts(), platform: Nerves.System.BR, platform_config: [ defconfig: "nerves_defconfig" ], # The :env key is an optional experimental feature for adding environment # variables to the crosscompile environment. These are intended for # llvm-based tooling that may need more precise processor information. env: [ {"TARGET_ARCH", "x86_64"}, {"TARGET_OS", "linux"}, {"TARGET_ABI", "gnu"} ], checksum: package_files() ] end defp deps do [ {:nerves, "~> 1.5.4 or ~> 1.6.0 or ~> 1.7.4", runtime: false}, {:nerves_system_br, "1.14.4", runtime: false}, {:nerves_toolchain_x86_64_nerves_linux_gnu, "~> 1.4.0", runtime: false}, {:nerves_system_linter, "~> 0.4", only: [:dev, :test], runtime: false}, {:ex_doc, "~> 0.22", only: :docs, runtime: false} ] end defp description do """ Nerves System - OnLogic CL210 """ end defp package do [ files: package_files(), licenses: ["Apache 2.0"], links: %{"Github" => "https://github.com/#{@github_organization}/#{@app}"} ] end defp package_files do [ "fwup_include", "rootfs_overlay", "busybox.fragment", "CHANGELOG.md", "Config.in", "external.mk", "fwup-revert.conf", "fwup.conf", "LICENSE", "linux-5.4.defconfig", "mix.exs", "nerves_defconfig", "post-build.sh", "post-createfs.sh", "README.md", "VERSION" ] end defp build_runner_opts() do if primary_site = System.get_env("BR2_PRIMARY_SITE") do [make_args: ["BR2_PRIMARY_SITE=#{primary_site}"]] else [] end end defp set_target() do if function_exported?(Mix, :target, 1) do apply(Mix, :target, [:target]) else System.put_env("MIX_TARGET", "target") end end end
23.94958
80
0.585614
f75c65838f5594ada23a4918f4c08f4727427c7b
2,766
ex
Elixir
apps/exth_crypto/lib/exth_crypto/hash/keccak.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/exth_crypto/lib/exth_crypto/hash/keccak.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/exth_crypto/lib/exth_crypto/hash/keccak.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule ExthCrypto.Hash.Keccak do @moduledoc """ Simple wrapper for Keccak function for Ethereum. Note: This module defines KECCAK as defined by Ethereum, which differs slightly than that assigned as the new SHA-3 variant. For SHA-3, a few constants have been changed prior to adoption by NIST, but after adoption by Ethereum. """ @type keccak_hash :: ExthCrypto.Hash.hash() @type keccak_mac :: {atom(), binary()} @doc """ Returns the keccak sha256 of a given input. ## Examples iex> ExthCrypto.Hash.Keccak.kec("hello world") <<71, 23, 50, 133, 168, 215, 52, 30, 94, 151, 47, 198, 119, 40, 99, 132, 248, 2, 248, 239, 66, 165, 236, 95, 3, 187, 250, 37, 76, 176, 31, 173>> iex> ExthCrypto.Hash.Keccak.kec(<<0x01, 0x02, 0x03>>) <<241, 136, 94, 218, 84, 183, 160, 83, 49, 140, 212, 30, 32, 147, 34, 13, 171, 21, 214, 83, 129, 177, 21, 122, 54, 51, 168, 59, 253, 92, 146, 57>> """ @spec kec(binary()) :: keccak_hash def kec(data) do :keccakf1600.sha3_256(data) end @doc """ Returns the keccak sha512 of a given input. ## Examples iex> ExthCrypto.Hash.Keccak.kec512("hello world") <<62, 226, 180, 0, 71, 184, 6, 15, 104, 198, 114, 66, 23, 86, 96, 244, 23, 77, 10, 245, 192, 29, 71, 22, 142, 194, 14, 214, 25, 176, 183, 196, 33, 129, 244, 10, 161, 4, 111, 57, 226, 239, 158, 252, 105, 16, 120, 42, 153, 142, 0, 19, 209, 114, 69, 137, 87, 149, 127, 172, 148, 5, 182, 125>> """ @spec kec512(binary()) :: keccak_hash def kec512(data) do :keccakf1600.sha3_512(data) end @doc """ Initializes a new Keccak mac stream. ## Examples iex> keccak_mac = ExthCrypto.Hash.Keccak.init_mac() iex> is_nil(keccak_mac) false """ @spec init_mac() :: keccak_mac def init_mac() do :keccakf1600.init(:sha3_256) end @doc """ Updates a given Keccak mac stream with the given secret and data, returning a new mac stream. ## Examples iex> keccak_mac = ExthCrypto.Hash.Keccak.init_mac() ...> |> ExthCrypto.Hash.Keccak.update_mac("data") iex> is_nil(keccak_mac) false """ @spec update_mac(keccak_mac, binary()) :: keccak_mac def update_mac(mac, data) do :keccakf1600.update(mac, data) end @doc """ Finalizes a given Keccak mac stream to produce the current hash. ## Examples iex> ExthCrypto.Hash.Keccak.init_mac() ...> |> ExthCrypto.Hash.Keccak.update_mac("data") ...> |> ExthCrypto.Hash.Keccak.final_mac() ...> |> ExthCrypto.Math.bin_to_hex "8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff" """ @spec final_mac(keccak_mac) :: keccak_hash def final_mac(mac) do :keccakf1600.final(mac) end end
29.115789
85
0.627621
f75ca6f0e3ddb1066eafe0151b470f8975debfbd
2,631
ex
Elixir
lib/maru/params/type_builder.ex
elixir-maru/maru_params
4bc1d05008e881136aff87667791ed4da1c12bd4
[ "WTFPL" ]
4
2021-12-29T06:45:02.000Z
2022-02-10T12:48:57.000Z
lib/maru/params/type_builder.ex
elixir-maru/maru_params
4bc1d05008e881136aff87667791ed4da1c12bd4
[ "WTFPL" ]
null
null
null
lib/maru/params/type_builder.ex
elixir-maru/maru_params
4bc1d05008e881136aff87667791ed4da1c12bd4
[ "WTFPL" ]
1
2021-12-29T06:45:03.000Z
2021-12-29T06:45:03.000Z
defmodule Maru.Params.TypeBuilder do defmacro __using__(options) do derive = Keyword.get(options, :derive, []) quote do require Protocol use Maru.Params.Builder Module.register_attribute(__MODULE__, :types, accumulate: true) import unquote(__MODULE__) @struct_derive unquote(derive) @before_compile unquote(__MODULE__) end end defmacro type(module, do: block) do type = Maru.Params.Builder.expand_alias(module, __CALLER__) quote do unquote(block) @types {unquote(type), :type, Maru.Params.Builder.pop_params(__ENV__)} end end defmacro type(module, options, do: block) do type = Maru.Params.Builder.expand_alias(module, __CALLER__) struct? = options == :struct || Keyword.get(options, :struct, false) struct_or_type = (struct? && :struct) || :type quote do unquote(block) @types {unquote(type), unquote(struct_or_type), Maru.Params.Builder.pop_params(__ENV__)} end end defmacro __before_compile__(%Macro.Env{module: module}) do derive = Module.get_attribute(module, :struct_derive) module |> Module.get_attribute(:types) |> Enum.map(fn {type, :type, params} -> params_runtime = Enum.map(params, &Map.get(&1, :runtime)) maru_type_module = Module.concat(Maru.Params.Types, type) quote do defmodule unquote(maru_type_module) do use Maru.Params.Type def parser_arguments, do: [:options] def parse(input, args) do options = Map.get(args, :options, []) unquote(params_runtime) |> Maru.Params.Runtime.parse_params(input, options) |> then(&{:ok, &1}) end end end {type, :struct, params} -> params_runtime = Enum.map(params, &Map.get(&1, :runtime)) maru_type_module = Module.concat(Maru.Params.Types, type) attributes = Enum.map(params, fn param -> param |> Map.get(:info) |> Keyword.get(:name) end) quote do defmodule unquote(type) do @derive unquote(derive) defstruct unquote(attributes) end defmodule unquote(maru_type_module) do use Maru.Params.Type def parser_arguments, do: [:options] def parse(input, args) do options = Map.get(args, :options, []) unquote(params_runtime) |> Maru.Params.Runtime.parse_params(input, options) |> then(&{:ok, struct(unquote(type), &1)}) end end end end) end end
29.561798
94
0.603573
f75cd3605af1e11c37e1861b6592fedf7e5c1f94
1,235
ex
Elixir
apps/service_aggregate/lib/aggregate/feed/consumer.ex
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/service_aggregate/lib/aggregate/feed/consumer.ex
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/service_aggregate/lib/aggregate/feed/consumer.ex
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule Aggregate.Feed.Consumer do @moduledoc """ Process for handling `GenStage` messages during profiling, sending a `aggregate_update` event. """ use GenStage require Logger @type init_opts :: [ dataset_id: String.t(), subset_id: String.t() ] @instance Aggregate.Application.instance() @spec start_link(init_opts) :: GenServer.on_start() def start_link(opts) do GenStage.start_link(__MODULE__, opts) end @impl GenStage def init(opts) do Logger.debug(fn -> "#{__MODULE__}(#{inspect(self())}): init with #{inspect(opts)}" end) {:consumer, %{ dataset_id: Keyword.fetch!(opts, :dataset_id), subset_id: Keyword.fetch!(opts, :subset_id) }} end @impl GenStage def handle_events(events, _from, state) do Logger.debug(fn -> "#{__MODULE__}(#{inspect(self())}): received events #{inspect(events)}" end) events |> Enum.map(fn event -> Aggregate.Update.new!( dataset_id: state.dataset_id, subset_id: state.subset_id, stats: event ) end) |> Enum.each(fn update -> Events.send_aggregate_update(@instance, "service_aggregate", update) end) {:noreply, [], state} end end
24.215686
99
0.635628
f75cf79d23f012dc7e226e5c290a4b117b923914
760
ex
Elixir
lib/pay_nl/bank.ex
smeevil/pay_nl
8b62ed5c01405aba432e56e8c2b6c5774da1470a
[ "WTFPL" ]
3
2017-10-03T12:30:57.000Z
2020-01-06T00:23:59.000Z
lib/pay_nl/bank.ex
smeevil/pay_nl
8b62ed5c01405aba432e56e8c2b6c5774da1470a
[ "WTFPL" ]
null
null
null
lib/pay_nl/bank.ex
smeevil/pay_nl
8b62ed5c01405aba432e56e8c2b6c5774da1470a
[ "WTFPL" ]
1
2019-02-11T11:12:17.000Z
2019-02-11T11:12:17.000Z
defmodule PayNL.Bank do @moduledoc """ This module provides a simple struct for the available banks of iDeal """ defstruct [:available, :image, :id, :issuer_id, :name, :swift] @spec json_to_struct({:ok, json :: map}) :: {:ok, list(%PayNL.Bank{})} | {:error, String.t} def json_to_struct({:ok, json}), do: {:ok, Enum.map(json, &parse_entry/1)} def json_to_struct(error), do: error @spec parse_entry(entry :: map) :: %PayNL.Bank{} def parse_entry(entry) do %PayNL.Bank{ available: (if entry["available"] == "1", do: true, else: false), image: entry["icon"], id: String.to_integer(entry["id"]), issuer_id: String.to_integer(entry["issuerId"]), name: entry["name"], swift: entry["swift"] } end end
34.545455
93
0.627632
f75cf9bc8a2207070fa79e9c58aec2c6887da016
685
ex
Elixir
backend/lib/functional_vote_web/router.ex
maxrchung/FunctionalVote
95c54c7614a74718e14c6fe74fd0bd4e84f85444
[ "MIT" ]
10
2020-03-13T12:56:06.000Z
2021-06-28T22:13:27.000Z
backend/lib/functional_vote_web/router.ex
maxrchung/FunctionalVote
95c54c7614a74718e14c6fe74fd0bd4e84f85444
[ "MIT" ]
132
2020-02-08T02:01:03.000Z
2022-02-18T20:38:38.000Z
backend/lib/functional_vote_web/router.ex
maxrchung/FunctionalVote
95c54c7614a74718e14c6fe74fd0bd4e84f85444
[ "MIT" ]
1
2021-03-17T06:22:55.000Z
2021-03-17T06:22:55.000Z
defmodule FunctionalVoteWeb.Router do use FunctionalVoteWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash # plug :protect_from_forgery plug :put_secure_browser_headers plug RemoteIp end pipeline :api do plug CORSPlug, origin: "http://localhost:3000" plug :accepts, ["json"] end scope "/", FunctionalVoteWeb do pipe_through :browser post "/poll", PollController, :create get "/poll/:poll_id", PollController, :show post "/vote", VoteController, :create end # Other scopes may use custom stacks. # scope "/api", FunctionalVoteWeb do # pipe_through :api # end end
21.40625
50
0.686131
f75d02870d4220cb8a138ed3d82a09687bd8f0de
1,102
ex
Elixir
episode-025/test/support/conn_case.ex
thaterikperson/elmseeds
72b09358926287ab4ea79893196d1ba002f190b3
[ "MIT" ]
84
2016-07-02T05:21:36.000Z
2021-02-12T22:45:45.000Z
episode-036/test/support/conn_case.ex
thaterikperson/elmseeds
72b09358926287ab4ea79893196d1ba002f190b3
[ "MIT" ]
3
2016-07-02T06:03:47.000Z
2017-06-03T14:11:06.000Z
episode-014/elm_is_fun/test/support/conn_case.ex
thaterikperson/elmseeds
72b09358926287ab4ea79893196d1ba002f190b3
[ "MIT" ]
6
2017-02-16T19:33:49.000Z
2019-04-05T19:27:17.000Z
defmodule ElmIsFun.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias ElmIsFun.Repo import Ecto import Ecto.Changeset import Ecto.Query import ElmIsFun.Router.Helpers # The default endpoint for testing @endpoint ElmIsFun.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(ElmIsFun.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(ElmIsFun.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
24.488889
70
0.705989
f75d079b6a69df03f5d63bad853b599fd178ef6c
7,398
exs
Elixir
test/cforum_web/controllers/events/attendee_controller_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
16
2019-04-04T06:33:33.000Z
2021-08-16T19:34:31.000Z
test/cforum_web/controllers/events/attendee_controller_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
294
2019-02-10T11:10:27.000Z
2022-03-30T04:52:53.000Z
test/cforum_web/controllers/events/attendee_controller_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
10
2019-02-10T10:39:24.000Z
2021-07-06T11:46:05.000Z
defmodule CforumWeb.Events.AttendeeControllerTest do use CforumWeb.ConnCase alias Cforum.Events.Event describe "new attendee" do setup [:setup_tests] test "renders form", %{conn: conn, event: event, user: user} do conn = conn |> login(user) |> get(Path.event_attendee_path(conn, :new, event)) assert html_response(conn, 200) =~ gettext("take place in event „%{event}“", event: event.name) end end describe "create attendee" do setup [:setup_tests] test "redirects to event#show when data is valid", %{conn: conn, event: event} do attrs = params_for(:attendee, event: event) conn = post(conn, Path.event_attendee_path(conn, :create, event), attendee: attrs) assert %{id: id} = cf_redirected_params(conn) assert redirected_to(conn) =~ Path.event_path(conn, :show, %Event{event_id: id}) conn = get(conn, Path.event_path(conn, :show, %Event{event_id: id})) assert html_response(conn, 200) =~ attrs[:name] end test "doesn't need a name when logged in", %{conn: conn, user: user, event: event} do attrs = params_for(:attendee, event: event) |> Map.delete(:name) conn = conn |> login(user) |> post(Path.event_attendee_path(conn, :create, event), attendee: attrs) assert %{id: id} = cf_redirected_params(conn) assert redirected_to(conn) =~ Path.event_path(conn, :show, %Event{event_id: id}) conn = get(conn, Path.event_path(conn, :show, %Event{event_id: id})) assert html_response(conn, 200) =~ user.username end test "renders errors when data is invalid", %{conn: conn, event: event} do conn = post(conn, Path.event_attendee_path(conn, :create, event), attendee: %{}) assert html_response(conn, 200) =~ gettext("take place in event „%{event}“", event: event.name) end end describe "edit cite" do setup [:setup_tests, :create_attendee] test "renders form for editing an attendee", %{conn: conn, event: event, admin: admin, attendee: attendee} do conn = conn |> login(admin) |> get(Path.event_attendee_path(conn, :edit, event, attendee)) assert html_response(conn, 200) =~ gettext( "take place in event „%{event}“: attendee „%{attendee}“", event: event.name, attendee: attendee.name ) end end describe "update attendee" do setup [:setup_tests, :create_attendee] test "redirects when data is valid", %{conn: conn, event: event, admin: admin, attendee: attendee} do conn = conn |> login(admin) |> put(Path.event_attendee_path(conn, :update, event, attendee), attendee: %{name: "Luke Skywalker"}) assert redirected_to(conn) == Path.event_path(conn, :show, event) conn = get(conn, Path.event_path(conn, :show, event)) assert html_response(conn, 200) =~ "Luke Skywalker" end test "renders errors when data is invalid", %{conn: conn, event: event, admin: admin, attendee: attendee} do conn = conn |> login(admin) |> put(Path.event_attendee_path(conn, :update, event, attendee), attendee: %{name: nil}) assert html_response(conn, 200) =~ gettext( "take place in event „%{event}“: attendee „%{attendee}“", event: event.name, attendee: attendee.name ) end end describe "delete attendee" do setup [:setup_tests, :create_attendee] test "deletes chosen attendee", %{conn: conn, event: event, attendee: attendee, admin: admin} do conn = conn |> login(admin) |> delete(Path.event_attendee_path(conn, :delete, event, attendee)) assert redirected_to(conn) == Path.event_path(conn, :show, event) assert_error_sent(404, fn -> get(conn, Path.event_attendee_path(conn, :edit, event, attendee)) end) end end describe "access rights" do setup [:setup_tests, :create_attendee] test "new is allowed as anonymous", %{conn: conn, event: event} do conn = get(conn, Path.event_attendee_path(conn, :new, event)) assert html_response(conn, 200) =~ gettext("take place in event „%{event}“", event: event.name) end test "new is allowed as logged in user", %{conn: conn, event: event, user1: user} do conn = conn |> login(user) |> get(Path.event_attendee_path(conn, :new, event)) assert html_response(conn, 200) =~ gettext("take place in event „%{event}“", event: event.name) end test "new isn't allowed as logged in user when already attending", %{conn: conn, event: event, user: user} do assert_error_sent(403, fn -> conn |> login(user) |> get(Path.event_attendee_path(conn, :new, event)) end) end test "responds with 403 on invisible event", %{conn: conn, hidden_event: event} do assert_error_sent(403, fn -> get(conn, Path.event_attendee_path(conn, :new, event)) end) end test "create is allowed as anonymous", %{conn: conn, event: event} do attrs = params_for(:attendee, event: event) conn = post(conn, Path.event_attendee_path(conn, :create, event), attendee: attrs) assert %{id: id} = cf_redirected_params(conn) assert redirected_to(conn) =~ Path.event_path(conn, :show, %Event{event_id: id}) end test "create is allowed as logged in user", %{conn: conn, user1: user, event: event} do attrs = params_for(:attendee, event: event) conn = conn |> login(user) |> post(Path.event_attendee_path(conn, :create, event), attendee: attrs) assert %{id: id} = cf_redirected_params(conn) assert redirected_to(conn) =~ Path.event_path(conn, :show, %Event{event_id: id}) end test "edit is not allowed for anonymous users", %{conn: conn, event: event, attendee: attendee} do assert_error_sent(403, fn -> get(conn, Path.event_attendee_path(conn, :edit, event, attendee)) end) end test "edit is allowed for logged in users", %{conn: conn, user: user, event: event, attendee: attendee} do conn = conn |> login(user) |> get(Path.event_attendee_path(conn, :edit, event, attendee)) assert html_response(conn, 200) end test "edit is not allowed for logged in users on foreign attendees", %{conn: conn, event: event, user: user} do attendee = insert(:attendee, event: event) assert_error_sent(403, fn -> get(login(conn, user), Path.event_attendee_path(conn, :edit, event, attendee)) end) end test "edit is allowed for admins on foreign attendees", %{conn: conn, event: event, attendee: attendee, admin: user} do conn = conn |> login(user) |> get(Path.event_attendee_path(conn, :edit, event, attendee)) assert html_response(conn, 200) end end defp create_attendee(%{event: event, user: user}) do attendee = insert(:attendee, event: event, user: user) {:ok, attendee: attendee} end defp setup_tests(_) do user = insert(:user) user1 = insert(:user) admin = build(:user) |> as_admin() |> insert() event = insert(:event, visible: true) hidden_event = insert(:event) {:ok, user: user, user1: user1, admin: admin, event: event, hidden_event: hidden_event} end end
35.73913
123
0.632603
f75d0f93d84914fef6aedd0cef310dd5dace5cd8
139
ex
Elixir
dingen/lib/dingen_web/controllers/page_controller.ex
rmoorman/dingen-2018011-tenants
02f3fa618b9a266340d4a4993420dc5641cec08e
[ "MIT" ]
null
null
null
dingen/lib/dingen_web/controllers/page_controller.ex
rmoorman/dingen-2018011-tenants
02f3fa618b9a266340d4a4993420dc5641cec08e
[ "MIT" ]
null
null
null
dingen/lib/dingen_web/controllers/page_controller.ex
rmoorman/dingen-2018011-tenants
02f3fa618b9a266340d4a4993420dc5641cec08e
[ "MIT" ]
null
null
null
defmodule DingenWeb.PageController do use DingenWeb, :controller def index(conn, _params) do render(conn, "index.html") end end
17.375
37
0.733813
f75d282cf75084f06be8a14a5ed16cfc96757f53
129
ex
Elixir
apps/ewallet_api/lib/ewallet_api/v1/sockets/endpoint.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
1
2018-12-07T06:21:21.000Z
2018-12-07T06:21:21.000Z
apps/ewallet_api/lib/ewallet_api/v1/sockets/endpoint.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/ewallet_api/lib/ewallet_api/v1/sockets/endpoint.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule EWalletAPI.V1.Endpoint do use Phoenix.Endpoint, otp_app: :ewallet_api socket("/socket", EWalletAPI.V1.Socket) end
21.5
45
0.775194
f75d4c7aef80d5e98e28bb416960f565ea4d8d81
1,760
ex
Elixir
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/wrapping_public_key.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/wrapping_public_key.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/wrapping_public_key.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudKMS.V1.Model.WrappingPublicKey do @moduledoc """ The public key component of the wrapping key. For details of the type of key this public key corresponds to, see the ImportMethod. ## Attributes * `pem` (*type:* `String.t`, *default:* `nil`) - The public key, encoded in PEM format. For more information, see the [RFC 7468](https://tools.ietf.org/html/rfc7468) sections for [General Considerations](https://tools.ietf.org/html/rfc7468#section-2) and [Textual Encoding of Subject Public Key Info] (https://tools.ietf.org/html/rfc7468#section-13). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :pem => String.t() | nil } field(:pem) end defimpl Poison.Decoder, for: GoogleApi.CloudKMS.V1.Model.WrappingPublicKey do def decode(value, options) do GoogleApi.CloudKMS.V1.Model.WrappingPublicKey.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudKMS.V1.Model.WrappingPublicKey do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.446809
354
0.742045
f75d62f59bcb716184e4363f4097c1876663c2fa
259
exs
Elixir
apps/emporium_api/priv/repo/migrations/20150822101958_create_category.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/emporium_api/priv/repo/migrations/20150822101958_create_category.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/emporium_api/priv/repo/migrations/20150822101958_create_category.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
defmodule EmporiumApi.Repo.Migrations.CreateCategory do use Ecto.Migration def change do create table(:emporium_categories) do add :name, :string add :permalink, :string add :parent_id, :integer timestamps end end end
17.266667
55
0.687259
f75d7e576b8a4a73b9d63b3ea88c4e094f8ab362
1,047
exs
Elixir
mix.exs
jeffgrunewald/divo_postgres
6a38670a8086dcbde8c98d18e5876812951727e0
[ "Apache-2.0" ]
2
2019-09-22T04:35:26.000Z
2020-12-15T02:56:47.000Z
mix.exs
jeffgrunewald/divo_postgres
6a38670a8086dcbde8c98d18e5876812951727e0
[ "Apache-2.0" ]
null
null
null
mix.exs
jeffgrunewald/divo_postgres
6a38670a8086dcbde8c98d18e5876812951727e0
[ "Apache-2.0" ]
1
2020-10-12T20:12:46.000Z
2020-10-12T20:12:46.000Z
defmodule DivoPostgres.MixProject do use Mix.Project @github "https://github.com/jeffgrunewald/divo_postgres" def project do [ app: :divo_postgres, version: "0.2.0", elixir: "~> 1.8", start_permanent: Mix.env() == :prod, deps: deps(), docs: docs(), package: package(), description: description(), source_url: @github, homepage_url: @github ] end def application do [ extra_applications: [:logger] ] end defp deps do [ {:divo, "~> 1.3"}, {:ex_doc, "~> 0.23", only: :dev} ] end defp description do "A pre-configured postgres docker-compose stack definition for integration testing with the divo library." end defp package do [ maintainers: ["jeffgrunewald"], licenses: ["Apache 2.0"], links: %{"GitHub" => @github} ] end defp docs do [ source_url: @github, extras: ["README.md"], source_url_pattern: "#{@github}/blob/master/%{path}#L%{line}" ] end end
19.036364
67
0.574021
f75d8f36622d1966e90158f3f8ac2c615b9eeca8
6,666
ex
Elixir
lib/ueberauth/strategy/qq.ex
dev800/ueberauth_qq
991260147ff2848b0efb88cff374db17b747b291
[ "MIT" ]
null
null
null
lib/ueberauth/strategy/qq.ex
dev800/ueberauth_qq
991260147ff2848b0efb88cff374db17b747b291
[ "MIT" ]
null
null
null
lib/ueberauth/strategy/qq.ex
dev800/ueberauth_qq
991260147ff2848b0efb88cff374db17b747b291
[ "MIT" ]
null
null
null
defmodule Ueberauth.Strategy.QQ do @moduledoc """ Provides an Ueberauth strategy for authenticating with QQ. ### Setup Include the provider in your configuration for Ueberauth config :ueberauth, Ueberauth, providers: [ qq: { Ueberauth.Strategy.QQ, [] } ] Then include the configuration for qq. config :ueberauth, Ueberauth.Strategy.QQ.OAuth, client_id: System.get_env("QQ_APPID"), client_secret: System.get_env("QQ_SECRET") If you haven't already, create a pipeline and setup routes for your callback handler pipeline :auth do Ueberauth.plug "/auth" end scope "/auth" do pipe_through [:browser, :auth] get "/:provider/callback", AuthController, :callback end Create an endpoint for the callback where you will handle the `Ueberauth.Auth` struct defmodule MyApp.AuthController do use MyApp.Web, :controller def callback_phase(%{ assigns: %{ ueberauth_failure: fails } } = conn, _params) do # do things with the failure end def callback_phase(%{ assigns: %{ ueberauth_auth: auth } } = conn, params) do # do things with the auth end end """ use Ueberauth.Strategy, uid_field: :uid, default_scope: "get_user_info", oauth2_module: Ueberauth.Strategy.QQ.OAuth alias Ueberauth.Auth.Info alias Ueberauth.Auth.Credentials alias Ueberauth.Auth.Extra @user_info_url "https://graph.qq.com/user/get_user_info" def oauth2_module, do: Ueberauth.Strategy.QQ.OAuth def secure_random_hex(n \\ 16) do n |> :crypto.strong_rand_bytes() |> Base.encode16(case: :lower) end @doc """ Handles the initial redirect to the qq authentication page. To customize the scope (permissions) that are requested by qq include them as part of your url: "/auth/qq?scope=snsapi_userinfo" You can also include a `state` param that qq will return to you. """ def handle_request!(conn) do conn = conn |> Plug.Conn.fetch_session() module = option(conn, :oauth2_module) scopes = conn.params["scope"] || option(conn, :default_scope) send_redirect_uri = Keyword.get(options(conn), :send_redirect_uri, true) config = conn.private[:ueberauth_request_options] |> Map.get(:options, []) redirect_uri = config[:redirect_uri] || callback_url(conn) state = secure_random_hex() params = if send_redirect_uri do [redirect_uri: redirect_uri, scope: scopes, state: state] else [scope: scopes, state: state] end conn |> Plug.Conn.put_session(:ueberauth_state, state) |> redirect!(apply(module, :authorize_url!, [params, [config: config]])) end @doc """ Handles the callback from QQ. When there is a failure from QQ the failure is included in the `ueberauth_failure` struct. Otherwise the information returned from QQ is returned in the `Ueberauth.Auth` struct. """ def handle_callback!(%Plug.Conn{params: %{"code" => code, "state" => state}} = conn) do conn = conn |> Plug.Conn.fetch_session() module = option(conn, :oauth2_module) client_options = conn.private |> Map.get(:ueberauth_request_options, %{}) |> Map.get(:options, []) options = [client_options: [config: client_options]] token = apply(module, :get_token!, [[code: code], [options: options]]) session_state = conn |> Plug.Conn.get_session(:ueberauth_state) conn = conn |> Plug.Conn.delete_session(:ueberauth_state) cond do state != session_state -> set_errors!(conn, [ error("StateMistake", "state mistake") ]) token.access_token |> to_string |> String.length() == 0 -> set_errors!(conn, [ error(token.other_params["error"], token.other_params["error_description"]) ]) true -> fetch_user(conn, token) end end @doc false def handle_callback!(conn) do set_errors!(conn, [error("missing_code", "No code received")]) end @doc """ Cleans up the private area of the connection used for passing the raw QQ response around during the callback. """ def handle_cleanup!(conn) do conn |> put_private(:qq_user, nil) |> put_private(:qq_token, nil) end @doc """ Fetches the uid field from the QQ response. This defaults to the option `uid_field` which in-turn defaults to `id` """ def uid(conn) do uid_field = conn |> option(:uid_field) |> to_string if conn.private[:qq_user] do conn.private.qq_user[uid_field] end end @doc """ Includes the credentials from the QQ response. """ def credentials(conn) do token = conn.private.qq_token scope_string = token.other_params["scope"] || "" scopes = String.split(scope_string, ",", trim: true) %Credentials{ token: token.access_token, refresh_token: token.refresh_token, expires_at: token.expires_at, token_type: token.token_type, expires: !!token.expires_at, scopes: scopes } end def present?(str), do: str |> to_string() |> String.length() > 0 @doc """ Fetches the fields to populate the info section of the `Ueberauth.Auth` struct. """ def info(conn) do user = conn.private.qq_user gender = case user["gender"] do "男" -> :male "女" -> :female "male" -> :male "female" -> :female _ -> :default end areas = [user["province"], user["city"]] |> Enum.filter(fn area -> present?(area) end) %Info{ nickname: user["nickname"], image: user["figureurl_qq"], gender: gender, areas: areas } end @doc """ Stores the raw information (including the token) obtained from the QQ callback. """ def extra(conn) do %Extra{ raw_info: %{ token: conn.private.qq_token, user: conn.private.qq_user } } end def fetch_user(conn, token) do conn = put_private(conn, :qq_token, token) # Will be better with Elixir 1.3 with/else case Ueberauth.Strategy.QQ.OAuth.get(token, @user_info_url) do {:ok, %OAuth2.Response{status_code: 401, body: _body}} -> set_errors!(conn, [error("token", "unauthorized")]) {:ok, %OAuth2.Response{status_code: _status_code, body: body}} -> put_private(conn, :qq_user, Jason.decode!(body)) {:error, %OAuth2.Error{reason: reason}} -> set_errors!(conn, [error("OAuth2", reason)]) end end defp option(conn, key) do Keyword.get(options(conn) || [], key, Keyword.get(default_options(), key)) end end
27.097561
116
0.637414
f75da3d4f6717180834ca6387ba98811b2e02516
330
exs
Elixir
test/linreg_web/live/page_live_test.exs
Tmw/linreg
b4dd10006ec875da1250cd5d2d7d21b551ed15e5
[ "MIT" ]
9
2020-05-25T19:54:41.000Z
2022-03-09T09:57:04.000Z
test/linreg_web/live/page_live_test.exs
Tmw/linreg
b4dd10006ec875da1250cd5d2d7d21b551ed15e5
[ "MIT" ]
2
2020-06-04T13:25:11.000Z
2020-06-07T14:31:30.000Z
test/linreg_web/live/page_live_test.exs
Tmw/linreg
b4dd10006ec875da1250cd5d2d7d21b551ed15e5
[ "MIT" ]
2
2021-01-14T17:03:01.000Z
2021-04-27T05:22:29.000Z
defmodule LinregWeb.PageLiveTest do use LinregWeb.ConnCase import Phoenix.LiveViewTest test "disconnected and connected render", %{conn: conn} do {:ok, page_live, disconnected_html} = live(conn, "/") assert disconnected_html =~ "Welcome to Phoenix!" assert render(page_live) =~ "Welcome to Phoenix!" end end
27.5
60
0.724242
f75da49c3abc325c56d326efe0a0c0620989fc63
533
exs
Elixir
test/log_results_test.exs
rawdamedia/quoil
8d7be55d15442e2f0cf8743d5ceb1dd5761e9356
[ "MIT" ]
1
2015-07-17T13:42:12.000Z
2015-07-17T13:42:12.000Z
test/log_results_test.exs
rawdamedia/quoil
8d7be55d15442e2f0cf8743d5ceb1dd5761e9356
[ "MIT" ]
3
2015-07-17T07:52:30.000Z
2016-03-16T11:34:48.000Z
test/log_results_test.exs
rawdamedia/quoil
8d7be55d15442e2f0cf8743d5ceb1dd5761e9356
[ "MIT" ]
1
2015-07-17T11:50:44.000Z
2015-07-17T11:50:44.000Z
defmodule LogResultsTest do use ExUnit.Case import Quoil.LogResults, only: [write_log: 1] import Quoil.ParseResults, only: [parse_result: 1] @test_ping1 "PING google.com (216.58.220.110): 56 data bytes\n\n--- google.com ping statistics ---\n5 packets transmitted, 5 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 51.321/53.851/55.948/1.647 ms\n" test "write_log to console" do assert write_log(parse_result({@test_ping1, "google.com", %{}, :std_out})) == {"google.com", %{}, :std_out} end end
41
227
0.707317
f75dab5da6f566e3e3fe161c425161407e777595
1,296
exs
Elixir
mix.exs
workplacearcade/ex_force
0e4b3ebb8b74214402d86264cb31fbf5c7a6a195
[ "MIT" ]
null
null
null
mix.exs
workplacearcade/ex_force
0e4b3ebb8b74214402d86264cb31fbf5c7a6a195
[ "MIT" ]
1
2021-03-25T03:35:37.000Z
2021-03-25T03:35:37.000Z
mix.exs
workplacearcade/ex_force
0e4b3ebb8b74214402d86264cb31fbf5c7a6a195
[ "MIT" ]
null
null
null
defmodule ExForce.Mixfile do use Mix.Project @version "0.4.1-dev" def project do [ app: :ex_force, version: @version, elixir: "~> 1.5", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), # hex description: "Simple Elixir wrapper for Salesforce REST API", # ex_doc name: "ExForce", source_url: "https://github.com/chulkilee/ex_force", homepage_url: "https://github.com/chulkilee/ex_force", docs: [main: "ExForce"], # test test_coverage: [tool: ExCoveralls] ] end def application do [] end defp deps do [ {:tesla, "~> 1.3"}, {:jason, "~> 1.0"}, {:bypass, "~> 2.1", only: :test}, {:credo, "~> 1.5", only: [:dev, :test], runtime: false}, {:dialyxir, "~> 1.1", only: :dev, runtime: false}, {:excoveralls, "~> 0.14", only: :test}, {:ex_doc, "~> 0.24", only: :dev, runtime: false}, {:inch_ex, "~> 2.0", only: [:dev, :test]} ] end defp package do [ licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/chulkilee/ex_force", "Changelog" => "https://github.com/chulkilee/ex_force/blob/main/CHANGELOG.md" }, maintainers: ["Chulki Lee"] ] end end
22.736842
85
0.531636
f75ddc0d8a8f21a30843db54bd8149e985caf658
1,886
exs
Elixir
clients/groups_settings/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/groups_settings/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/groups_settings/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.GroupsSettings.Mixfile do use Mix.Project @version "0.10.0" def project() do [ app: :google_api_groups_settings, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/groups_settings" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Groups Settings API client library. Manages permission levels and related settings of a group. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/groups_settings", "Homepage" => "https://developers.google.com/google-apps/groups-settings/get_started" } ] end end
28.149254
106
0.663309
f75de8184b57620d6f366c9185a481b975c78a52
649
exs
Elixir
base/fc_base/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
base/fc_base/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
base/fc_base/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
defmodule FCBase.MixProject do use Mix.Project def project do [ app: :fc_base, version: "0.1.0", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:fc_support, path: "../fc_support"}, {:fc_state_storage, path: "../fc_state_storage"}, {:commanded_eventstore_adapter, "~> 0.3"}, {:phoenix_pubsub, "~> 1.1"}, {:ok, "~> 2.0"} ] end end
20.28125
59
0.565485
f75dea4bb5c3872f3851f628341362772eb0c247
2,122
ex
Elixir
lib/segment/sender.ex
pierrefourgeaud/analytics-elixir
c05f2236263bddad905a770ff91ad4d2ee86d63d
[ "MIT" ]
null
null
null
lib/segment/sender.ex
pierrefourgeaud/analytics-elixir
c05f2236263bddad905a770ff91ad4d2ee86d63d
[ "MIT" ]
null
null
null
lib/segment/sender.ex
pierrefourgeaud/analytics-elixir
c05f2236263bddad905a770ff91ad4d2ee86d63d
[ "MIT" ]
null
null
null
defmodule Segment.Analytics.Sender do @moduledoc """ The `Segment.Analytics.Sender` service implementation is an alternative to the default Batcher to send every event as it is called. The HTTP call is made with an async `Task` to not block the GenServer. This will not guarantee ordering. The `Segment.Analytics.Batcher` should be preferred in production but this module will emulate the implementaiton of the original library if you need that or need events to be as real-time as possible. """ use GenServer alias Segment.Analytics.{Track, Identify, Screen, Alias, Group, Page} @doc """ Start the `Segment.Analytics.Sender` GenServer with an Segment HTTP Source API Write Key """ @spec start_link(String.t()) :: GenServer.on_start() def start_link(api_key) do client = Segment.Http.client(api_key) GenServer.start_link(__MODULE__, client, name: String.to_atom(api_key)) end @doc """ Start the `Segment.Analytics.Sender` GenServer with an Segment HTTP Source API Write Key and a Tesla Adapter. This is mainly used for testing purposes to override the Adapter with a Mock. """ @spec start_link(String.t(), Tesla.adapter()) :: GenServer.on_start() def start_link(api_key, adapter) do client = Segment.Http.client(api_key, adapter) GenServer.start_link(__MODULE__, {client, :queue.new()}, name: __MODULE__) end # client @doc """ Make a call to Segment with an event. Should be of type `Track, Identify, Screen, Alias, Group or Page`. This event will be sent immediately and asyncronously """ @spec call(Segment.segment_event(), pid() | __MODULE__.t()) :: :ok def call(%{__struct__: mod} = event, pid \\ __MODULE__) when mod in [Track, Identify, Screen, Alias, Group, Page] do callp(event, pid) end # GenServer Callbacks @impl true def init(client) do {:ok, client} end @impl true def handle_cast({:send, event}, client) do Task.start_link(fn -> Segment.Http.send(client, event) end) {:noreply, client} end # Helpers defp callp(event, pid), do: GenServer.cast(pid, {:send, event}) end
36.586207
144
0.708294
f75df8f7482e8fb59bfbdbecb2f1c84f55ed2707
801
exs
Elixir
test/controllers/ph_controller_test.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
test/controllers/ph_controller_test.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
test/controllers/ph_controller_test.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
defmodule BioMonitor.PhControllerTest do use BioMonitor.ConnCase @moduledoc """ Test cases for PhController The commented tests won't pass unless the board is connected. """ setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end # test "returns current ph value", %{conn: conn} do # conn = get conn, ph_path(conn, :current) # assert json_response(conn, 200)["current_value"] != nil # end # test "sets offset ph value", %{conn: conn} do # conn = get conn, ph_path(conn, :current, %{"offset" => "#{0.3}"}) # assert json_response(conn, 200)["current_value"] != nil # end test "fails to return current ph value", %{conn: conn} do conn = get conn, ph_path(conn, :current) assert response(conn, 422) end end
28.607143
71
0.652934
f75e0d7917570b77639947927c52ecf4d04aacce
174
exs
Elixir
priv/repo/migrations/20191204032058_add_email_to_users.exs
t00lmaker/elixir-bank
41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0
[ "MIT" ]
4
2020-05-05T18:37:28.000Z
2022-01-05T00:56:19.000Z
priv/repo/migrations/20191204032058_add_email_to_users.exs
t00lmaker/elixir-bank
41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0
[ "MIT" ]
21
2019-12-01T15:32:02.000Z
2019-12-19T13:10:36.000Z
priv/repo/migrations/20191204032058_add_email_to_users.exs
t00lmaker/elixir-bank
41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0
[ "MIT" ]
2
2020-09-12T16:07:11.000Z
2020-12-11T06:46:45.000Z
defmodule Bank.Repo.Migrations.AddEmailToUsers do use Ecto.Migration def change do alter table(:clients) do add :email, :string, null: false end end end
17.4
49
0.701149
f75e166bcfec1eef92f8c996d9ac93cf316d437e
6,988
ex
Elixir
apps/rig_cloud_events/lib/rig_cloud_events/parser/partial_parser.ex
arana3/reactive-interaction-gateway
793648bcc5b8b05fc53df1f5f97818fb40ca84be
[ "Apache-2.0" ]
518
2017-11-09T13:10:49.000Z
2022-03-28T14:29:50.000Z
apps/rig_cloud_events/lib/rig_cloud_events/parser/partial_parser.ex
arana3/reactive-interaction-gateway
793648bcc5b8b05fc53df1f5f97818fb40ca84be
[ "Apache-2.0" ]
270
2017-11-10T00:11:34.000Z
2022-02-27T13:08:16.000Z
apps/rig_cloud_events/lib/rig_cloud_events/parser/partial_parser.ex
arana3/reactive-interaction-gateway
793648bcc5b8b05fc53df1f5f97818fb40ca84be
[ "Apache-2.0" ]
67
2017-12-19T20:16:37.000Z
2022-03-31T10:43:04.000Z
defmodule RigCloudEvents.Parser.PartialParser do @moduledoc """ Error-tolerant reader for JSON encoded CloudEvents. Interprets the passed data structure as little as possible. The idea comes from the CloudEvents spec that states that JSON payloads ("data") are encoded along with the envelope ("context attributes"). This parser only interprets fields that are required for RIG to operate and skips the (potentially large) data payload. """ @behaviour RigCloudEvents.Parser alias RigCloudEvents.Parser alias Jaxon.Event, as: JaxonToken alias Jaxon.Parser, as: JaxonParser @type t :: [JaxonToken.t()] @impl true @spec parse(Parser.json_string()) :: t defdelegate parse(json), to: JaxonParser # --- @impl true @spec context_attribute(t, Parser.attribute()) :: {:ok, value :: any} | {:error, {:not_found, Parser.attribute(), t}} | {:error, {:non_scalar_value, Parser.attribute(), t}} | {:error, any} def context_attribute(tokens, attr_name) do value(tokens, attr_name) end # --- @impl true @spec extension_attribute( t, Parser.extension(), Parser.attribute() ) :: {:ok, value :: any} | {:error, {:not_found, Parser.attribute(), t}} | {:error, {:not_an_object | :non_scalar_value, Parser.attribute(), t}} | {:error, any} def extension_attribute(tokens, extension_name, attr_name) do case apply_lens(tokens, extension_name) do [] -> {:error, {:not_found, extension_name, tokens}} [:start_object | _] = extension -> value(extension, attr_name) tokens -> {:error, {:not_an_object, extension_name, tokens}} end end # --- @impl true @spec find_value(t, Parser.json_pointer()) :: {:ok, value :: any} | {:error, {:not_found, location :: String.t(), t}} | {:error, {:non_scalar_value, location :: String.t(), t}} | {:error, any} def find_value(json_tokens, "/" <> json_pointer) do # See https://tools.ietf.org/html/rfc6901#section-4 reference_tokens = for token <- String.split(json_pointer, "/"), do: token |> String.replace("~1", "/") |> String.replace("~0", "~") # We can't do much if the pointer goes into data and data is encoded.. if points_into_encoded_data(json_tokens, reference_tokens) do {:error, :cannot_extract_from_encoded_data} else do_find_value(json_tokens, reference_tokens) end end def find_value(tokens, "" = _the_whole_document), do: {:error, {:non_scalar_value, "", tokens}} def find_value(_tokens, "#" <> _), do: raise("The URI fragment identifier representation is not supported.") # --- defp points_into_encoded_data(json_tokens, reference_tokens) defp points_into_encoded_data(json_tokens, [ref_token | rest]) when ref_token == "data" and rest != [] do # `data` is encoded if, and only if, `contenttype` is set. case value(json_tokens, "contenttype") do {:error, {:not_found, _, _}} -> # `contenttype` is not set, so `data` must be already parsed. false {:ok, _} -> # `contenttype` is set, so `data` is still encoded. true end end defp points_into_encoded_data(_, _), do: false # --- defp do_find_value(json_tokens, reference_tokens) defp do_find_value(json_tokens, [ref_token | []]), do: value(json_tokens, ref_token) defp do_find_value(json_tokens, [ref_token | remaining_ref_tokens]), do: apply_lens(json_tokens, ref_token) |> do_find_value(remaining_ref_tokens) # --- defp value(tokens, prop) do case apply_lens(tokens, prop) do [] -> {:error, {:not_found, prop, tokens}} [{:error, error} | _] -> {:error, error} [{_, value}] -> {:ok, value} [nil] -> {:ok, nil} [:start_object | _] = tokens -> {:error, {:non_scalar_value, prop, tokens}} [:start_array | _] = tokens -> {:error, {:non_scalar_value, prop, tokens}} end end def apply_lens(tokens, attr_name) do case tokens do [{:string, ^attr_name} | [:colon | tokens]] -> read_val(tokens) [{:string, _key} | [:colon | tokens]] -> skip_val(tokens) |> apply_lens(attr_name) [:start_object | tokens] -> apply_lens(tokens, attr_name) [:end_object] -> [] [] -> [] [{:error, _} | _] -> tokens [:start_array | _] -> :not_implemented end end # --- defp read_val(tokens), do: do_read_val(tokens, tokens) # Assumes tokens is right after a colon. defp do_read_val(all_tokens, remaining_tokens, n_processed \\ 0, obj_depth \\ 0, arr_depth \\ 0) # The exit condition: comma or end of input at the root level: defp do_read_val(tokens, [:comma | _], n_processed, 0, 0), do: Enum.take(tokens, n_processed) defp do_read_val(tokens, [:end_object], n_processed, 0, 0), do: Enum.take(tokens, n_processed) defp do_read_val(tokens, [], n_processed, 0, 0), do: Enum.take(tokens, n_processed) defp do_read_val(tokens, [:start_object | rest], n_processed, obj_depth, arr_depth), do: do_read_val(tokens, rest, n_processed + 1, obj_depth + 1, arr_depth) defp do_read_val(tokens, [:end_object | rest], n_processed, obj_depth, arr_depth) when obj_depth > 0, do: do_read_val(tokens, rest, n_processed + 1, obj_depth - 1, arr_depth) defp do_read_val(tokens, [:start_array | rest], n_processed, obj_depth, arr_depth), do: do_read_val(tokens, rest, n_processed + 1, obj_depth, arr_depth + 1) defp do_read_val(tokens, [:end_array | rest], n_processed, obj_depth, arr_depth) when arr_depth > 0, do: do_read_val(tokens, rest, n_processed + 1, obj_depth, arr_depth - 1) # "Skip" all other tokens: defp do_read_val(tokens, [_ | rest], n_processed, obj_depth, arr_depth), do: do_read_val(tokens, rest, n_processed + 1, obj_depth, arr_depth) # --- # Assumes tokens is right after a colon and skips until right before the next key or the end. defp skip_val(tokens, obj_depth \\ 0, arr_depth \\ 0) defp skip_val([:start_object | tokens], obj_depth, arr_depth) do skip_val(tokens, obj_depth + 1, arr_depth) end defp skip_val([:end_object | tokens], obj_depth, arr_depth) when obj_depth > 0 do skip_val(tokens, obj_depth - 1, arr_depth) end defp skip_val([:start_array | tokens], obj_depth, arr_depth) do skip_val(tokens, obj_depth, arr_depth + 1) end defp skip_val([:end_array | tokens], obj_depth, arr_depth) when arr_depth > 0 do skip_val(tokens, obj_depth, arr_depth - 1) end defp skip_val([_ | tokens], obj_depth, arr_depth) when obj_depth > 0 or arr_depth > 0 do skip_val(tokens, obj_depth, arr_depth) end defp skip_val([{_, _} | tokens], 0, 0), do: skip_val(tokens, 0, 0) defp skip_val([nil | tokens], 0, 0), do: skip_val(tokens, 0, 0) defp skip_val([:comma | tokens], 0, 0), do: tokens # The root object: defp skip_val([:end_object], 0, 0), do: [] defp skip_val([], _, _), do: [] end
34.94
98
0.651689
f75e33fe39c6cf112ee96c0e164e62276fc6096f
1,153
ex
Elixir
test/support/channel_case.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
3
2021-03-19T10:39:02.000Z
2021-07-25T19:54:09.000Z
test/support/channel_case.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
204
2020-11-27T06:00:31.000Z
2022-03-25T08:08:16.000Z
test/support/channel_case.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
null
null
null
defmodule PhoenixStarterWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use PhoenixStarterWeb.ChannelCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels import Phoenix.ChannelTest import PhoenixStarterWeb.ChannelCase # The default endpoint for testing @endpoint PhoenixStarterWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(PhoenixStarter.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(PhoenixStarter.Repo, {:shared, self()}) end :ok end end
28.121951
76
0.737207
f75ec3d97b1770cd66856be23f7c73b821b75775
353
exs
Elixir
priv/repo/seeds.exs
Baradoy/topshelf
bd3d5f96b3d3840990231cf244cc5f14bd807997
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
Baradoy/topshelf
bd3d5f96b3d3840990231cf244cc5f14bd807997
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
Baradoy/topshelf
bd3d5f96b3d3840990231cf244cc5f14bd807997
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Topshelf.Repo.insert!(%Topshelf.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
29.416667
61
0.708215
f75ed46368667f0a818c01729b4127fb51a6ea52
675
exs
Elixir
examples/mm/factorial1.exs
renanlage/programming-elixir-book
71e58398269cde2b76a377d28cc906fb528c4134
[ "MIT" ]
8
2018-08-26T08:10:08.000Z
2021-04-05T16:05:05.000Z
examples/mm/factorial1.exs
renanlage/programming-elixir-book
71e58398269cde2b76a377d28cc906fb528c4134
[ "MIT" ]
null
null
null
examples/mm/factorial1.exs
renanlage/programming-elixir-book
71e58398269cde2b76a377d28cc906fb528c4134
[ "MIT" ]
1
2019-10-08T09:56:43.000Z
2019-10-08T09:56:43.000Z
defmodule Factorial do def of(0), do: 1 def of(n) when n > 0, do: n * of(n-1) end defmodule Sum do def of(0), do: 0 def of(n), do: n + of(n-1) end defmodule Length do def of([]), do: 0 def of([_|tail]), do: 1 + of(tail) end IO.puts(Factorial.of(0) == 1) IO.puts(Factorial.of(1) == 1) IO.puts(Factorial.of(2) == 2) IO.puts(Factorial.of(3) == 6) IO.puts(Factorial.of(4) == 24) IO.puts(Sum.of(0) == 0) IO.puts(Sum.of(1) == 1) IO.puts(Sum.of(2) == 3) IO.puts(Sum.of(3) == 6) IO.puts(Sum.of(4) == 10) IO.puts(Length.of([]) == 0) IO.puts(Length.of([1]) == 1) IO.puts(Length.of([9, 1]) == 2) IO.puts(Length.of([5, 9, 1]) == 3) IO.puts(Length.of([1, 5, 9, 1]) == 4)
20.454545
39
0.568889
f75edc2aefb8a4a7447b05cf59d5238b6d3824fc
478
exs
Elixir
config/config.exs
FritzFlorian/flickr_client
b749e5e126e1a4f5d05d8822c13f7568644674c2
[ "MIT" ]
null
null
null
config/config.exs
FritzFlorian/flickr_client
b749e5e126e1a4f5d05d8822c13f7568644674c2
[ "MIT" ]
null
null
null
config/config.exs
FritzFlorian/flickr_client
b749e5e126e1a4f5d05d8822c13f7568644674c2
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config config :logger, level: :info case Mix.env do :test -> config :flickr_client, flickr_key: "FLICKR_KEY", flickr_endpoint: FlickrMockEndpoint :dev -> config :flickr_client, flickr_key: System.get_env("FLICKR_KEY") || "FLICKR_KEY_UNSET", flickr_endpoint: FlickrClient.FlickrHttpEndpoint _ -> true end
22.761905
69
0.717573
f75ee7b4bc61a43855613a36ad5e25ffe7a2b505
353
exs
Elixir
test/blog_linter_test.exs
buys-fran/blog_linter_ex
bf0debb5b66b196d06b3c29e612ad416d720c971
[ "MIT" ]
2
2021-04-30T04:15:25.000Z
2021-05-13T17:31:17.000Z
test/blog_linter_test.exs
buys-fran/blog_linter_ex
bf0debb5b66b196d06b3c29e612ad416d720c971
[ "MIT" ]
null
null
null
test/blog_linter_test.exs
buys-fran/blog_linter_ex
bf0debb5b66b196d06b3c29e612ad416d720c971
[ "MIT" ]
2
2021-04-30T04:15:29.000Z
2021-06-08T13:08:23.000Z
defmodule BlogLinterTest do use ExUnit.Case doctest BlogLinter test "reads the files in a given path" do assert BlogLinter.file_names("./blogposts") == ["post1.markdown", "post2.markdown"] end test "reads the content of a file" do content = BlogLinter.process_file("./blogposts", "post1.markdown") assert content != "" end end
25.214286
87
0.70255
f75ef4b5df615236043fad79cdeed2c132f0af60
6,086
ex
Elixir
clients/classroom/lib/google_api/classroom/v1/model/student_submission.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/classroom/lib/google_api/classroom/v1/model/student_submission.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/classroom/lib/google_api/classroom/v1/model/student_submission.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Classroom.V1.Model.StudentSubmission do @moduledoc """ Student submission for course work. StudentSubmission items are generated when a CourseWork item is created. StudentSubmissions that have never been accessed (i.e. with `state` = NEW) may not have a creation time or update time. ## Attributes * `alternateLink` (*type:* `String.t`, *default:* `nil`) - Absolute link to the submission in the Classroom web UI. Read-only. * `assignedGrade` (*type:* `float()`, *default:* `nil`) - Optional grade. If unset, no grade was set. This value must be non-negative. Decimal (i.e. non-integer) values are allowed, but will be rounded to two decimal places. This may be modified only by course teachers. * `assignmentSubmission` (*type:* `GoogleApi.Classroom.V1.Model.AssignmentSubmission.t`, *default:* `nil`) - Submission content when course_work_type is ASSIGNMENT. Students can modify this content using google.classroom.Work.ModifyAttachments. * `associatedWithDeveloper` (*type:* `boolean()`, *default:* `nil`) - Whether this student submission is associated with the Developer Console project making the request. See google.classroom.Work.CreateCourseWork for more details. Read-only. * `courseId` (*type:* `String.t`, *default:* `nil`) - Identifier of the course. Read-only. * `courseWorkId` (*type:* `String.t`, *default:* `nil`) - Identifier for the course work this corresponds to. Read-only. * `courseWorkType` (*type:* `String.t`, *default:* `nil`) - Type of course work this submission is for. Read-only. * `creationTime` (*type:* `DateTime.t`, *default:* `nil`) - Creation time of this submission. This may be unset if the student has not accessed this item. Read-only. * `draftGrade` (*type:* `float()`, *default:* `nil`) - Optional pending grade. If unset, no grade was set. This value must be non-negative. Decimal (i.e. non-integer) values are allowed, but will be rounded to two decimal places. This is only visible to and modifiable by course teachers. * `id` (*type:* `String.t`, *default:* `nil`) - Classroom-assigned Identifier for the student submission. This is unique among submissions for the relevant course work. Read-only. * `late` (*type:* `boolean()`, *default:* `nil`) - Whether this submission is late. Read-only. * `multipleChoiceSubmission` (*type:* `GoogleApi.Classroom.V1.Model.MultipleChoiceSubmission.t`, *default:* `nil`) - Submission content when course_work_type is MULTIPLE_CHOICE_QUESTION. * `shortAnswerSubmission` (*type:* `GoogleApi.Classroom.V1.Model.ShortAnswerSubmission.t`, *default:* `nil`) - Submission content when course_work_type is SHORT_ANSWER_QUESTION. * `state` (*type:* `String.t`, *default:* `nil`) - State of this submission. Read-only. * `submissionHistory` (*type:* `list(GoogleApi.Classroom.V1.Model.SubmissionHistory.t)`, *default:* `nil`) - The history of the submission (includes state and grade histories). Read-only. * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Last update time of this submission. This may be unset if the student has not accessed this item. Read-only. * `userId` (*type:* `String.t`, *default:* `nil`) - Identifier for the student that owns this submission. Read-only. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :alternateLink => String.t(), :assignedGrade => float(), :assignmentSubmission => GoogleApi.Classroom.V1.Model.AssignmentSubmission.t(), :associatedWithDeveloper => boolean(), :courseId => String.t(), :courseWorkId => String.t(), :courseWorkType => String.t(), :creationTime => DateTime.t(), :draftGrade => float(), :id => String.t(), :late => boolean(), :multipleChoiceSubmission => GoogleApi.Classroom.V1.Model.MultipleChoiceSubmission.t(), :shortAnswerSubmission => GoogleApi.Classroom.V1.Model.ShortAnswerSubmission.t(), :state => String.t(), :submissionHistory => list(GoogleApi.Classroom.V1.Model.SubmissionHistory.t()), :updateTime => DateTime.t(), :userId => String.t() } field(:alternateLink) field(:assignedGrade) field(:assignmentSubmission, as: GoogleApi.Classroom.V1.Model.AssignmentSubmission) field(:associatedWithDeveloper) field(:courseId) field(:courseWorkId) field(:courseWorkType) field(:creationTime, as: DateTime) field(:draftGrade) field(:id) field(:late) field(:multipleChoiceSubmission, as: GoogleApi.Classroom.V1.Model.MultipleChoiceSubmission) field(:shortAnswerSubmission, as: GoogleApi.Classroom.V1.Model.ShortAnswerSubmission) field(:state) field(:submissionHistory, as: GoogleApi.Classroom.V1.Model.SubmissionHistory, type: :list) field(:updateTime, as: DateTime) field(:userId) end defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.StudentSubmission do def decode(value, options) do GoogleApi.Classroom.V1.Model.StudentSubmission.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.StudentSubmission do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.859155
190
0.694545
f75f26e950972f7d53771693ba36ca14bd4d6757
5,144
ex
Elixir
lib/iex/lib/iex/config.ex
britto/elixir
1f6e7093cff4b68dada60b924399bc8404d39a7e
[ "Apache-2.0" ]
2
2020-06-02T18:00:28.000Z
2021-12-10T03:21:42.000Z
lib/iex/lib/iex/config.ex
britto/elixir
1f6e7093cff4b68dada60b924399bc8404d39a7e
[ "Apache-2.0" ]
1
2020-09-14T16:23:33.000Z
2021-03-25T17:38:59.000Z
lib/iex/lib/iex/config.ex
britto/elixir
1f6e7093cff4b68dada60b924399bc8404d39a7e
[ "Apache-2.0" ]
null
null
null
defmodule IEx.Config do @moduledoc false use Agent @table __MODULE__ @agent __MODULE__ @keys [ :colors, :inspect, :history_size, :default_prompt, :continuation_prompt, :alive_prompt, :alive_continuation_prompt, :width ] # Read API def configuration() do Application.get_all_env(:iex) |> Keyword.take(@keys) end def width() do columns = columns() value = Application.get_env(:iex, :width) || 80 min(value, columns) end defp columns() do case :io.columns() do {:ok, width} -> width {:error, _} -> 80 end end def started?() do Process.whereis(@agent) != nil end def history_size() do Application.fetch_env!(:iex, :history_size) end def default_prompt() do Application.fetch_env!(:iex, :default_prompt) end def continuation_prompt() do Application.get_env(:iex, :continuation_prompt, default_prompt()) end def alive_prompt() do Application.fetch_env!(:iex, :alive_prompt) end def alive_continuation_prompt() do Application.get_env(:iex, :alive_continuation_prompt, alive_prompt()) end def color(color) do color(color, Application.get_env(:iex, :colors, [])) end defp color(color, colors) do if colors_enabled?(colors) do case Keyword.fetch(colors, color) do {:ok, value} -> value :error -> default_color(color) end else nil end end defp colors_enabled?(colors) do case Keyword.fetch(colors, :enabled) do {:ok, enabled} -> enabled :error -> IO.ANSI.enabled?() end end # Used by default on evaluation cycle defp default_color(:eval_interrupt), do: [:yellow] defp default_color(:eval_result), do: [:yellow] defp default_color(:eval_error), do: [:red] defp default_color(:eval_info), do: [:normal] defp default_color(:stack_info), do: [:red] defp default_color(:blame_diff), do: [:red] # Used by ls defp default_color(:ls_directory), do: [:blue] defp default_color(:ls_device), do: [:green] # Used by inspect defp default_color(:syntax_colors) do [ atom: :cyan, string: :green, list: :default_color, boolean: :magenta, nil: :magenta, tuple: :default_color, binary: :default_color, map: :default_color ] end # Used by ansi docs defp default_color(doc_color) do IO.ANSI.Docs.default_options() |> Keyword.fetch!(doc_color) end def ansi_docs() do colors = Application.get_env(:iex, :colors, []) enabled = colors_enabled?(colors) [width: width(), enabled: enabled] ++ colors end def inspect_opts() do Application.get_env(:iex, :inspect, []) |> Keyword.put_new_lazy(:width, &width/0) |> update_syntax_colors() end defp update_syntax_colors(opts) do colors = Application.get_env(:iex, :colors, []) if syntax_colors = color(:syntax_colors, colors) do reset = [:reset | List.wrap(color(:eval_result, colors))] syntax_colors = [reset: reset] ++ syntax_colors Keyword.update(opts, :syntax_colors, syntax_colors, &Keyword.merge(syntax_colors, &1)) else opts end end # Agent API def start_link(_) do Agent.start_link(__MODULE__, :handle_init, [], name: @agent) end def after_spawn(fun) do Agent.update(@agent, __MODULE__, :handle_after_spawn, [fun]) end def after_spawn() do :ets.lookup_element(@table, :after_spawn, 2) end def configure(options) do Agent.update(@agent, __MODULE__, :handle_configure, [options]) end # Agent callbacks def handle_init do :ets.new(@table, [:named_table, :public]) true = :ets.insert_new(@table, after_spawn: []) @table end def handle_after_spawn(tab, fun) do :ets.update_element(tab, :after_spawn, {2, [fun | after_spawn()]}) end def handle_configure(tab, options) do Enum.each(options, &validate_option/1) configuration() |> Keyword.merge(options, &merge_option/3) |> update_configuration() tab end defp update_configuration(config) do Enum.each(config, fn {key, value} when key in @keys -> Application.put_env(:iex, key, value) end) end defp merge_option(:colors, old, new) when is_list(new), do: Keyword.merge(old, new) defp merge_option(:inspect, old, new) when is_list(new), do: Keyword.merge(old, new) defp merge_option(_key, _old, new), do: new defp validate_option({:colors, new}) when is_list(new), do: :ok defp validate_option({:inspect, new}) when is_list(new), do: :ok defp validate_option({:history_size, new}) when is_integer(new), do: :ok defp validate_option({:default_prompt, new}) when is_binary(new), do: :ok defp validate_option({:continuation_prompt, new}) when is_binary(new), do: :ok defp validate_option({:alive_prompt, new}) when is_binary(new), do: :ok defp validate_option({:alive_continuation_prompt, new}) when is_binary(new), do: :ok defp validate_option({:width, new}) when is_integer(new), do: :ok defp validate_option(option) do raise ArgumentError, "invalid configuration #{inspect(option)}" end end
24.850242
92
0.664075
f75f6bea77346f99db08afabfe67ab00d49f27ff
7,852
ex
Elixir
deps/makeup/lib/makeup/registry.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
deps/makeup/lib/makeup/registry.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
deps/makeup/lib/makeup/registry.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
defmodule Makeup.Registry do @moduledoc """ A registry that allows users to dynamically register new makeup lexers. Lexers should register themselves on application start. That way, you can add support for new programming languages by depending on the relevant lexers. This is useful for projects such as ExDoc, which might contain code in a number of different programming languages. """ @name_registry_key :lexer_name_registry @extension_registry_key :lexer_extension_registry # -------------------------------------------------------------------------- # Public API # -------------------------------------------------------------------------- @doc """ Gets the list of supported language names. """ def supported_language_names() do Map.keys(get_name_registry()) end @doc """ Gets the list of supported language extensions. """ def supported_file_extensions() do Map.keys(get_extension_registry()) end @doc """ Adds a new lexer to Makeup's registry under the given `name`. This function expects a language name (e.g. `"elixir"`) and a pair containing a `lexer` and a list of `options`. You might want to use the `Makeup.Registry.register_lexer/2` function instead. ## Examples alias Makeup.Lexers.ElixirLexer alias Makeup.Registry Registry.register_lexer_with_name("elixir", {ElixirLexer, []}) Registry.register_lexer_with_name("iex", {ElixirLexer, []}) """ def register_lexer_with_name(name, {lexer, options}) when is_binary(name) do old_registry = get_name_registry() updated_registry = Map.put(old_registry, name, {lexer, options}) put_name_registry(updated_registry) end @doc """ Adds a new lexer to Makeup's registry under the given `extension`. This function expects a file extension (e.g. `"ex"`) and a pair containing a `lexer` and a list of `options`. You might want to use the `Makeup.Registry.register_lexer/2` function instead. ## Examples alias Makeup.Lexers.ElixirLexer alias Makeup.Registry Registry.register_lexer_with_extension("ex"), {ElixirLexer, []}) Registry.register_lexer_with_extension("exs"), {ElixirLexer, []}) """ def register_lexer_with_extension(name, {lexer, options}) when is_binary(name) do old_registry = get_extension_registry() updated_registry = Map.put(old_registry, name, {lexer, options}) put_extension_registry(updated_registry) end @doc """ Add a new lexer to Makeup's registry under the given names and extensions. Expects a lexer `lexer` and a number of options: * `:options` (default: `[]`) - the lexer options. If your lexer doesn't take any options, you'll want the default value of `[]`. * `:names` (default: `[]`) - a list of strings with the language names for the lexer. Language names are strings, not atoms. Even if there is only one valid name, you must supply a list with that name. To avoid filling the registry unnecessarily, you should normalize your language names to lowercase strings. If the caller wants to support upper case language names for some reason, they can normalize the language names themselves. * `:extensions` (default: `[]`) - the list of file extensions for the languages supported by the lexer. For example, the elixir lexer should support the `"ex"` and `"exs"` file extensions. The extensions should not include the dot. That is, you should register `"ex"` and not `".ex"`. Even if there is only a supported extension, you must supply a list. ## Example alias Makeup.Registry alias Makeup.Lexers.ElixirLexer # The `:options` key is not required Registry.register_lexer(ElixirLexer, names: ["elixir", "iex"], extensions: ["ex", "exs"]) """ def register_lexer(lexer, opts) do options = Keyword.get(opts, :options, []) names = Keyword.get(opts, :names, []) extensions = Keyword.get(opts, :extensions, []) # Associate the lexer with the names for name <- names, do: register_lexer_with_name(name, {lexer, options}) # Associate the lexer with the extensions for extension <- extensions, do: register_lexer_with_extension(extension, {lexer, options}) end @doc """ Fetches the lexer from Makeup's registry with the given `name`. Returns either `{:ok, {lexer, options}}` or `:error`. This behaviour is based on `Map.fetch/2`. """ def fetch_lexer_by_name(name) do Map.fetch(get_name_registry(), name) end @doc """ Fetches the lexer from Makeup's registry with the given `name`. Returns either `{lexer, options}` or raises a `KeyError`. This behaviour is based on `Map.fetch!/2`. """ def fetch_lexer_by_name!(name) do Map.fetch!(get_name_registry(), name) end @doc """ Gets the lexer from Makeup's registry with the given `name`. Returns either `{lexer, options}` or the `default` value (which by default is `nil`). This behaviour is based on `Map.get/3`. """ def get_lexer_by_name(name, default \\ nil) do Map.get(get_name_registry(), name, default) end @doc """ Fetches a lexer from Makeup's registry with the given file `extension`. Returns either `{:ok, {lexer, options}}` or `:error`. This behaviour is based on `Map.fetch/2`. """ def fetch_lexer_by_extension(name) do Map.fetch(get_extension_registry(), name) end @doc """ Fetches the lexer from Makeup's registry with the given file `extension`. Returns either `{:ok, {lexer, options}}` or raises a `KeyError`. This behaviour is based on `Map.fetch/2`. """ def fetch_lexer_by_extension!(name) do Map.fetch!(get_extension_registry(), name) end @doc """ Gets the lexer from Makeup's registry with the given file `extension`. Returns either `{lexer, options}` or the `default` value (which by default is `nil`). This behaviour is based on `Map.get/3`. """ def get_lexer_by_extension(name, default \\ nil) do Map.get(get_extension_registry(), name, default) end # --------------------------------------------------------------------------- # Functions not meant to be used outside Makeup # --------------------------------------------------------------------------- # This functions are meant to be run on application startup # or to be used as helpers in Makeup's internal tests. # They are not meant to be invoked by users of Makeup @doc false def create_name_registry() do Application.put_env(:makeup, @name_registry_key, %{}) end @doc false def create_extension_registry() do Application.put_env(:makeup, @extension_registry_key, %{}) end # The `clean_*_registry` are actually the same as the `create_*_registry`, # but that's because of implementation details, so it makes sense to have # separate groups of functions @doc false def clean_name_registry() do put_name_registry(%{}) end @doc false def clean_extension_registry() do put_extension_registry(%{}) end # ---------------------------------------------------------------------------- # Private helper functions # ---------------------------------------------------------------------------- defp get_name_registry() do Application.get_env(:makeup, @name_registry_key) end defp put_name_registry(registry) do Application.put_env(:makeup, @name_registry_key, registry) end defp get_extension_registry() do Application.get_env(:makeup, @extension_registry_key) end defp put_extension_registry(registry) do Application.put_env(:makeup, @extension_registry_key, registry) end end
34.13913
108
0.643021
f75f7ffab3eda98a2478e4e82b2df44ab4d26d09
5,531
exs
Elixir
test/ex_oauth2_provider/oauth2/token/strategy/refresh_token_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
test/ex_oauth2_provider/oauth2/token/strategy/refresh_token_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
test/ex_oauth2_provider/oauth2/token/strategy/refresh_token_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
defmodule ExOauth2Provider.Token.Strategy.RefreshTokenTest do use ExOauth2Provider.TestCase alias ExOauth2Provider.{Config, AccessTokens, Token, Token.RefreshToken} alias ExOauth2Provider.Test.{Fixtures, QueryHelpers} alias Dummy.{OauthAccessTokens.OauthAccessToken, Repo} @client_id "Jf5rM8hQBc" @client_secret "secret" @invalid_client_error %{ error: :invalid_client, error_description: "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method." } @invalid_request_error %{ error: :invalid_request, error_description: "The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed." } setup do user = Fixtures.resource_owner() application = Fixtures.application( resource_owner: user, uid: @client_id, secret: @client_secret, scopes: "app:read app:write" ) access_token = Fixtures.access_token( resource_owner: user, application: application, use_refresh_token: true, scopes: "app:read" ) valid_request = %{ "client_id" => @client_id, "client_secret" => @client_secret, "grant_type" => "refresh_token", "refresh_token" => access_token.refresh_token } {:ok, %{access_token: access_token, valid_request: valid_request}} end test "#grant/2 error when invalid client", %{valid_request: valid_request} do request_invalid_client = Map.merge(valid_request, %{"client_id" => "invalid"}) assert Token.grant(request_invalid_client, otp_app: :ex_oauth2_provider) == {:error, @invalid_client_error, :unprocessable_entity} end test "#grant/2 error when invalid secret", %{valid_request: valid_request} do request_invalid_client = Map.merge(valid_request, %{"client_secret" => "invalid"}) assert Token.grant(request_invalid_client, otp_app: :ex_oauth2_provider) == {:error, @invalid_client_error, :unprocessable_entity} end test "#grant/2 error when missing token", %{valid_request: valid_request} do params = Map.delete(valid_request, "refresh_token") assert Token.grant(params, otp_app: :ex_oauth2_provider) == {:error, @invalid_request_error, :bad_request} end test "#grant/2 error when invalid token", %{valid_request: valid_request} do params = Map.merge(valid_request, %{"refresh_token" => "invalid"}) assert Token.grant(params, otp_app: :ex_oauth2_provider) == {:error, @invalid_request_error, :bad_request} end test "#grant/2 error when access token owned by another client", %{ valid_request: valid_request, access_token: access_token } do new_application = Fixtures.application(uid: "new_app") QueryHelpers.change!(access_token, application_id: new_application.id) assert Token.grant(valid_request, otp_app: :ex_oauth2_provider) == {:error, @invalid_request_error, :bad_request} end test "#grant/2 error when access token has been revoked", %{ valid_request: valid_request, access_token: access_token } do QueryHelpers.change!(access_token, revoked_at: DateTime.utc_now()) assert Token.grant(valid_request, otp_app: :ex_oauth2_provider) == {:error, @invalid_request_error, :bad_request} end test "#grant/2 returns access token", %{ valid_request: valid_request, access_token: access_token } do assert {:ok, new_access_token} = Token.grant(valid_request, otp_app: :ex_oauth2_provider) access_token = Repo.get_by(OauthAccessToken, id: access_token.id) new_access_token = Repo.get_by(OauthAccessToken, token: new_access_token.access_token) refute new_access_token.token == access_token.token assert new_access_token.resource_owner_id == access_token.resource_owner_id assert new_access_token.application_id == access_token.application_id assert new_access_token.scopes == access_token.scopes assert new_access_token.expires_in == Config.access_token_expires_in(otp_app: :ex_oauth2_provider) assert new_access_token.previous_refresh_token == access_token.refresh_token assert AccessTokens.is_revoked?(access_token) end test "#grant/2 returns access token with custom response handler", %{ valid_request: valid_request } do assert {:ok, body} = RefreshToken.grant(valid_request, otp_app: :ex_oauth2_provider, access_token_response_body_handler: {__MODULE__, :access_token_response_body_handler} ) access_token = Repo.get_by(OauthAccessToken, token: body.access_token) assert body.custom_attr == access_token.inserted_at end test "#grant/2 when refresh_token_revoked_on_use? == false", %{ valid_request: valid_request, access_token: access_token } do assert {:ok, new_access_token} = RefreshToken.grant(valid_request, otp_app: :ex_oauth2_provider, revoke_refresh_token_on_use: false ) access_token = Repo.get_by(OauthAccessToken, id: access_token.id) new_access_token = Repo.get_by(OauthAccessToken, token: new_access_token.access_token) assert new_access_token.previous_refresh_token == "" refute AccessTokens.is_revoked?(access_token) end def access_token_response_body_handler(body, access_token) do Map.merge(body, %{custom_attr: access_token.inserted_at}) end end
35.683871
132
0.715061
f75f9b364190030a8972f29c2a74ec2d4cc056d6
1,445
exs
Elixir
mix.exs
matthewlehner/ueberauth_shopify
6f38569034bee0e4b393ba49351d215092c9c4eb
[ "MIT" ]
3
2016-11-07T19:04:50.000Z
2017-02-04T01:38:45.000Z
mix.exs
matthewlehner/ueberauth_shopify
6f38569034bee0e4b393ba49351d215092c9c4eb
[ "MIT" ]
2
2017-04-03T18:43:55.000Z
2020-01-16T16:53:58.000Z
mix.exs
matthewlehner/ueberauth_shopify
6f38569034bee0e4b393ba49351d215092c9c4eb
[ "MIT" ]
8
2017-09-19T10:38:27.000Z
2022-01-27T01:35:26.000Z
defmodule UeberauthShopify.Mixfile do use Mix.Project @version "0.1.2" @url "https://github.com/alistairstead/ueberauth_shopify" def project do [app: :ueberauth_shopify, version: @version, elixir: "~> 1.3", package: package(), build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, source_url: @url, homepage_url: @url, description: description(), deps: deps(), docs: docs()] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger, :ueberauth, :oauth2]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [{:oauth2, "~> 0.8.0"}, {:ueberauth, "~> 0.4.0"}, {:earmark, "~> 1.0", only: :dev}, {:ex_doc, "~> 0.14.0", only: :dev}] end defp docs do [extras: docs_extras()] end defp docs_extras do ["README.md"] end defp description do """ An Ueberauth strategy for authenticating your application with Shopify. """ end defp package do [files: ["lib", "mix.exs", "README.md", "LICENSE"], maintainers: ["Alistair Stead"], licenses: ["MIT"], links: %{"GitHub": @url}] end end
21.893939
77
0.595848
f75fa0d036a7b14a12d2121ad54f5586bf3aa81f
1,309
ex
Elixir
lib/langue/formatter/json/serializer.ex
suryatmodulus/accent
6aaf34075c33f3d9d84d38237af4a39b594eb808
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
lib/langue/formatter/json/serializer.ex
suryatmodulus/accent
6aaf34075c33f3d9d84d38237af4a39b594eb808
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
lib/langue/formatter/json/serializer.ex
doc-ai/accent
e337e16f3658cc0728364f952c0d9c13710ebb06
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule Langue.Formatter.Json.Serializer do @behaviour Langue.Formatter.Serializer alias Langue.Utils.NestedSerializerHelper def serialize(%{entries: entries}) do render = entries |> serialize_json |> Kernel.<>("\n") %Langue.Formatter.SerializerResult{render: render} end def serialize_json(entries) do %{"" => entries} |> Enum.with_index(-1) |> Enum.map(&NestedSerializerHelper.map_value(elem(&1, 0), elem(&1, 1))) |> List.first() |> elem(1) |> encode_json() end def encode_json(content) do content |> Enum.map(&add_extra/1) |> (&{&1}).() |> :jsone.encode([:native_utf8, :native_forward_slash, {:indent, 2}, {:space, 1}, {:float_format, [{:decimals, 4}, :compact]}]) |> prettify_json() end def prettify_json(string) do string |> String.replace(~r/\" : (\"|{|\[|null|false|true|\d)/, "\": \\1") end defp add_extra({key, [{_, _} | _] = values}), do: {key, {Enum.map(values, &add_extra/1)}} defp add_extra({key, values}) when is_list(values), do: {key, Enum.map(values, &add_extra/1)} defp add_extra({key, values}), do: {key, add_extra(values)} defp add_extra(values = [{_key, _} | _]), do: {Enum.map(values, &add_extra/1)} defp add_extra(nil), do: :null defp add_extra(value), do: value end
29.75
131
0.624141
f75fe00267bcc61b0b05973aa914ba3eb07b2683
1,518
ex
Elixir
test/support/data_case.ex
wagncarv/blog_new
bcfde533df5109cfa68b33362db56ef728090b02
[ "MIT" ]
null
null
null
test/support/data_case.ex
wagncarv/blog_new
bcfde533df5109cfa68b33362db56ef728090b02
[ "MIT" ]
null
null
null
test/support/data_case.ex
wagncarv/blog_new
bcfde533df5109cfa68b33362db56ef728090b02
[ "MIT" ]
null
null
null
defmodule BlogNew.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use BlogNew.DataCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate alias Ecto.Adapters.SQL.Sandbox using do quote do alias BlogNew.Repo import Ecto import Ecto.Changeset import Ecto.Query import BlogNew.DataCase end end setup tags do pid = Sandbox.start_owner!(BlogNew.Repo, shared: not tags[:async]) on_exit(fn -> Sandbox.stop_owner(pid) end) :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Regex.replace(~r"%{(\w+)}", message, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end
28.641509
77
0.694335
f7600ce10a69b88aaa7743d1e490aaad0732785e
667
exs
Elixir
mix.exs
Highjhacker/Ark-Elixir-Example
7daec76e839cb291ebc191b840845f17342be617
[ "MIT" ]
1
2018-04-22T05:15:59.000Z
2018-04-22T05:15:59.000Z
mix.exs
Highjhacker/Ark-Elixir-Example
7daec76e839cb291ebc191b840845f17342be617
[ "MIT" ]
null
null
null
mix.exs
Highjhacker/Ark-Elixir-Example
7daec76e839cb291ebc191b840845f17342be617
[ "MIT" ]
null
null
null
defmodule ArkElixirExample.Mixfile do use Mix.Project def project do [ app: :ark_elixir_example, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, escript: [main_module: ArkElixirExample], deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, {:ark_elixir, "~> 0.1.2"} ] end end
21.516129
88
0.589205
f7602c5864d4d7acecd628eb5207d93e9b509372
2,885
ex
Elixir
clients/datastream/lib/google_api/datastream/v1/model/private_connection.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/datastream/lib/google_api/datastream/v1/model/private_connection.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/datastream/lib/google_api/datastream/v1/model/private_connection.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Datastream.V1.Model.PrivateConnection do @moduledoc """ The PrivateConnection resource is used to establish private connectivity between Datastream and a customer's network. ## Attributes * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The create time of the resource. * `displayName` (*type:* `String.t`, *default:* `nil`) - Required. Display name. * `error` (*type:* `GoogleApi.Datastream.V1.Model.Error.t`, *default:* `nil`) - Output only. In case of error, the details of the error in a user-friendly format. * `labels` (*type:* `map()`, *default:* `nil`) - Labels. * `name` (*type:* `String.t`, *default:* `nil`) - Output only. The resource's name. * `state` (*type:* `String.t`, *default:* `nil`) - Output only. The state of the Private Connection. * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The update time of the resource. * `vpcPeeringConfig` (*type:* `GoogleApi.Datastream.V1.Model.VpcPeeringConfig.t`, *default:* `nil`) - VPC Peering Config. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :createTime => DateTime.t() | nil, :displayName => String.t() | nil, :error => GoogleApi.Datastream.V1.Model.Error.t() | nil, :labels => map() | nil, :name => String.t() | nil, :state => String.t() | nil, :updateTime => DateTime.t() | nil, :vpcPeeringConfig => GoogleApi.Datastream.V1.Model.VpcPeeringConfig.t() | nil } field(:createTime, as: DateTime) field(:displayName) field(:error, as: GoogleApi.Datastream.V1.Model.Error) field(:labels, type: :map) field(:name) field(:state) field(:updateTime, as: DateTime) field(:vpcPeeringConfig, as: GoogleApi.Datastream.V1.Model.VpcPeeringConfig) end defimpl Poison.Decoder, for: GoogleApi.Datastream.V1.Model.PrivateConnection do def decode(value, options) do GoogleApi.Datastream.V1.Model.PrivateConnection.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Datastream.V1.Model.PrivateConnection do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.426471
166
0.689428
f76033daf66b1cda87edee946645e41e710681ce
1,738
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/instance_group_managers_list_managed_instances_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/compute/lib/google_api/compute/v1/model/instance_group_managers_list_managed_instances_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/instance_group_managers_list_managed_instances_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse do @moduledoc """ ## Attributes * `managedInstances` (*type:* `list(GoogleApi.Compute.V1.Model.ManagedInstance.t)`, *default:* `nil`) - [Output Only] The list of instances in the managed instance group. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :managedInstances => list(GoogleApi.Compute.V1.Model.ManagedInstance.t()) } field(:managedInstances, as: GoogleApi.Compute.V1.Model.ManagedInstance, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse do def decode(value, options) do GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.423077
174
0.757768
f7606c6ca67e5fb2e5b45a59b600375c20767bd2
893
exs
Elixir
spec/generated_examples_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/generated_examples_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/generated_examples_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
defmodule GeneratedExamplesSpec do use ESpec, async: true subject 1..5 Enum.map(1..3, fn n -> it do: is_expected().to(have(unquote(n))) end) context "with description" do subject(24) Enum.map(2..4, fn n -> it "is divisible by #{n}" do expect(rem(subject(), unquote(n))).to(be(0)) end end) end context "using a module attribute instead of unquote()" do subject(%{a: 1, b: 2, c: 3}) Enum.each([:a, :b, :c], fn key -> @key key it "it has key #{key}" do is_expected().to(have_key(@key)) end end) end context "with description and shared data" do subject([:c]) before do: {:shared, list: [:a, :b]} Enum.each([:a, :b, :c], fn value -> @value value it "it + shared has value #{@value}" do expect(subject() ++ shared.list).to(have(@value)) end end) end end
20.767442
60
0.555431
f76089a1aa2f3b6015df275b9b84b4fb4e97b200
1,380
ex
Elixir
lib/rfx/util/source.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
31
2021-05-29T22:57:04.000Z
2022-03-13T16:24:57.000Z
lib/rfx/util/source.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
4
2021-06-04T23:34:38.000Z
2021-07-16T16:01:20.000Z
lib/rfx/util/source.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
4
2021-06-11T13:10:04.000Z
2022-02-11T13:33:16.000Z
defmodule Rfx.Util.Source do @moduledoc """ A utility module for source code manipulation. """ alias Rfx.Util.Str @base_diff "/tmp/rfx_base_diff" @doc """ Returns updated text, edited according to the Sourceror edit function. """ def edit(code, efun) do code |> Sourceror.parse_string() |> Sourceror.postwalk(efun) |> Sourceror.to_string() end @doc """ Returns diff text, given two source texts. """ def diff(old_source, new_source), do: diff({old_source, new_source}) def diff({src1, src2}) do rand = Str.rand_str() path1 = @base_diff <> "/src1_" <> rand path2 = @base_diff <> "/src2_" <> rand File.mkdir(@base_diff) File.write(path1, src1 |> Str.terminate_nl()) File.write(path2, src2 |> Str.terminate_nl()) {diff, _} = System.cmd("diff", [path1, path2]) File.rm(path1) File.rm(path2) diff end @doc """ Returns modified source, given old source text, and a diff text. """ def patch(source, diff) do ext = Str.rand_str() spath = @base_diff <> "/patch_src_" <> ext dpath = @base_diff <> "/patch_dif_" <> ext File.mkdir(@base_diff) File.write(spath, source) File.write(dpath, diff |> Str.terminate_nl()) opts = [spath, dpath, "-s", "-o", "-"] {new_src, _} = System.cmd("patch", opts) File.rm(spath) File.rm(dpath) new_src end end
23.793103
72
0.621014
f760aec8141d586c17733cb213e6e8090d905db5
944
exs
Elixir
test/webmonitor/checker_test.exs
rawcodehq/webmonitor
1397c74cb04434d18eb08e447c2c91d23ca97962
[ "MIT" ]
5
2016-07-05T20:31:46.000Z
2021-03-20T20:11:48.000Z
test/webmonitor/checker_test.exs
rawcodehq/webmonitor
1397c74cb04434d18eb08e447c2c91d23ca97962
[ "MIT" ]
null
null
null
test/webmonitor/checker_test.exs
rawcodehq/webmonitor
1397c74cb04434d18eb08e447c2c91d23ca97962
[ "MIT" ]
1
2016-07-18T23:00:46.000Z
2016-07-18T23:00:46.000Z
defmodule Webmonitor.CheckerTest do use Webmonitor.ModelCase import Webmonitor.Checker alias Webmonitor.Checker.Stats test "ping returns :ok when website is up" do assert {:ok, %Stats{}} = ping("http://httpstat.us/200") end test "ping returns the response time in milliseconds" do {:ok, %Stats{response_time_ms: response_time_ms}} = ping("http://httpstat.us/200") assert response_time_ms > 50 end test "ping returns :error when website returns a redirect" do assert {:error, _} = ping("http://httpstat.us/302") end test "ping returns :error when website returns a 40x code" do assert {:error, _} = ping("http://httpstat.us/404") end test "ping returns :error when website returns a 50x code" do assert {:error, _} = ping("http://httpstat.us/501") end test "ping returns :error when dns doesn't resolve" do assert {:error, _} = ping("http://abracadabra.mujju.and.zainu") end end
28.606061
86
0.691737
f760e54b9a391cfed20ee7c7cb67c2e62d385352
1,126
ex
Elixir
web_finngen_r8/lib/risteys/mortality_stats.ex
vincent-octo/risteys
5bb1e70b78988770048b91b42fad025faf98d84a
[ "MIT" ]
null
null
null
web_finngen_r8/lib/risteys/mortality_stats.ex
vincent-octo/risteys
5bb1e70b78988770048b91b42fad025faf98d84a
[ "MIT" ]
null
null
null
web_finngen_r8/lib/risteys/mortality_stats.ex
vincent-octo/risteys
5bb1e70b78988770048b91b42fad025faf98d84a
[ "MIT" ]
null
null
null
defmodule Risteys.MortalityStats do use Ecto.Schema import Ecto.Changeset schema "mortality_stats" do field :phenocode_id, :id field :lagged_hr_cut_year, :integer field :hr, :float field :hr_ci_min, :float field :hr_ci_max, :float field :pvalue, :float field :n_individuals, :integer field :absolute_risk, :float timestamps() end @doc false def changeset(mortality_stats, attrs) do mortality_stats |> cast(attrs, [:phenocode_id, :lagged_hr_cut_year, :hr, :hr_ci_min, :hr_ci_max, :pvalue, :n_individuals, :absolute_risk]) |> validate_required([:phenocode_id, :lagged_hr_cut_year, :hr, :hr_ci_min, :hr_ci_max, :pvalue, :n_individuals, :absolute_risk]) |> validate_inclusion(:lagged_hr_cut_year, [0, 1, 5, 15]) |> validate_number(:hr, greater_than_or_equal_to: 0.0) |> validate_number(:pvalue, greater_than_or_equal_to: 0.0, less_than: 1) |> validate_number(:n_individuals, greater_than: 5) |> validate_number(:absolute_risk, greater_than_or_equal_to: 0.0, less_than: 1) |> unique_constraint(:phenocode_id, name: :phenocode_hrlag) end end
35.1875
132
0.719361
f76114038872d38587b557c04902f4d573b74909
139
exs
Elixir
test/test_helper.exs
flaviogrossi/horde
89059a28db7f5c23c8f4d044024a738a379a80cb
[ "MIT" ]
3
2019-11-11T17:00:04.000Z
2019-11-20T22:01:06.000Z
test/test_helper.exs
flaviogrossi/horde
89059a28db7f5c23c8f4d044024a738a379a80cb
[ "MIT" ]
null
null
null
test/test_helper.exs
flaviogrossi/horde
89059a28db7f5c23c8f4d044024a738a379a80cb
[ "MIT" ]
null
null
null
# Disable until we can get this working on CircleCI # :ok = LocalCluster.start() # Application.ensure_all_started(:horde) ExUnit.start()
19.857143
51
0.755396
f761291a9b0456a6c0583d5a87936d44b457aa15
105
ex
Elixir
lib/rescueImages.ex
szTheory/elixir-leaseweb
98be9c7cc496b52d7b12d4986078d1b68fca1e71
[ "MIT" ]
1
2018-09-07T15:56:14.000Z
2018-09-07T15:56:14.000Z
lib/rescueImages.ex
szTheory/elixir-leaseweb
98be9c7cc496b52d7b12d4986078d1b68fca1e71
[ "MIT" ]
null
null
null
lib/rescueImages.ex
szTheory/elixir-leaseweb
98be9c7cc496b52d7b12d4986078d1b68fca1e71
[ "MIT" ]
2
2017-02-11T03:00:58.000Z
2020-03-03T21:21:42.000Z
defmodule LeaseWeb.RescueImages do def list() do LeaseWeb.Client.get("rescueImages") end end
15
40
0.714286
f76133da6d0431259cef44a5d5b8d4b2388bcda7
1,292
exs
Elixir
test/macro_expansion_test.exs
ijcd/taggart
603aac1bea00f17ad2eebdb40e3720d4f42fc5a7
[ "Apache-2.0" ]
36
2017-10-27T10:08:37.000Z
2021-12-26T07:54:05.000Z
test/macro_expansion_test.exs
ijcd/taggart
603aac1bea00f17ad2eebdb40e3720d4f42fc5a7
[ "Apache-2.0" ]
null
null
null
test/macro_expansion_test.exs
ijcd/taggart
603aac1bea00f17ad2eebdb40e3720d4f42fc5a7
[ "Apache-2.0" ]
4
2017-11-08T15:58:15.000Z
2020-04-21T21:34:13.000Z
defmodule MacroExpansionTest do use Taggart.ConnCase use Taggart.HTML test "basic ast" do expanded = quote location: :keep do div(class: "foo", id: "bar") do "content" end end assert {:div, _, [[class: "foo", id: "bar"], [do: "content"]]} = expanded end test "desugar div/1 (content)" do expanded = quote location: :keep do div("content") end |> Macro.expand_once(__ENV__) assert {:div, _, [[], [do: "content"]]} = expanded end test "desugar div/1 tag(do: content)" do expanded = quote location: :keep do div do "content" end end |> Macro.expand_once(__ENV__) assert {:div, _, [[], [do: "content"]]} = expanded end test "desugar div/2, (content, attrs)" do expanded = quote location: :keep do div("content", do: "do_arg", id: "bar") end |> Macro.expand_once(__ENV__) assert {:div, _, [[do: "do_arg", id: "bar"], [do: "content"]]} = expanded end test "desugar div/2, (content, do_arg)" do expanded = quote location: :keep do div("content", do: "do_arg") end |> Macro.expand_once(__ENV__) assert {:div, _, [[do: "do_arg"], [do: "content"]]} = expanded end end
22.275862
77
0.549536
f76141a2e72ca7a8605f47df2278804ea3064a8d
2,599
exs
Elixir
test/index/compiler_test.exs
fanuniverse/elasticfusion
fea34d51051f5bb3c3d9e33fd99b2d5baf261f7e
[ "CC0-1.0" ]
null
null
null
test/index/compiler_test.exs
fanuniverse/elasticfusion
fea34d51051f5bb3c3d9e33fd99b2d5baf261f7e
[ "CC0-1.0" ]
null
null
null
test/index/compiler_test.exs
fanuniverse/elasticfusion
fea34d51051f5bb3c3d9e33fd99b2d5baf261f7e
[ "CC0-1.0" ]
null
null
null
defmodule Elasticfusion.Index.CompilerTest do use ExUnit.Case defmodule CompilerTestIndex do use Elasticfusion.Index index_name "compiler_test_index" document_type "compiler_test_type" index_settings %{number_of_shards: 1} mapping %{ tags: %{type: :keyword}, stars: %{type: :integer}, date: %{type: :date} } serialize &(%{tags: &1.tags, stars: &1.stars, date: &1.created_at}) keyword_field :tags queryable_fields [date: "created at", stars: "stars"] def_transform "starred by", fn (_, value, _) -> %{term: %{stars: value}} end def_transform "found in", fn (_, "my favorites", %{name: username}) -> %{term: %{tags: "faved by #{username}"}} end end test "compiles index_name/0, document_type/0, index_settings/0" do assert CompilerTestIndex.index_name() == "compiler_test_index" assert CompilerTestIndex.document_type() == "compiler_test_type" assert CompilerTestIndex.index_settings() == %{number_of_shards: 1} end test "compiles queryable_fields/0 that includes transforms" do assert CompilerTestIndex.queryable_fields() == ["created at", "stars", "found in", "starred by"] end test "compiles serialize/1" do assert CompilerTestIndex.serialize( %{tags: "peridot", stars: 5, created_at: "feb 2017"}) == %{tags: "peridot", stars: 5, date: "feb 2017"} end test "defines transform/3 clauses for queryable_fields" do import Elasticfusion.Utils, only: [parse_nl_date: 1] import CompilerTestIndex, only: [transform: 4] assert transform("created at", "earlier than", "2 months ago", nil) == %{range: %{date: %{lt: parse_nl_date("2 months ago")}}} assert transform("created at", "later than", "2 months ago", nil) == %{range: %{date: %{gt: parse_nl_date("2 months ago")}}} assert transform("created at", nil, "2 months ago", nil) == %{term: %{date: parse_nl_date("2 months ago")}} assert transform("stars", "less than", "10", nil) == %{range: %{stars: %{lt: "10"}}} assert transform("stars", "more than", "10", nil) == %{range: %{stars: %{gt: "10"}}} assert transform("stars", nil, "10", nil) == %{term: %{stars: "10"}} end test "defines transform/3 clauses for custom transforms" do import CompilerTestIndex, only: [transform: 4] assert transform("starred by", nil, "5", nil) == %{term: %{stars: "5"}} assert transform("found in", nil, "my favorites", %{name: "cool username"}) == %{term: %{tags: "faved by cool username"}} end end
30.940476
82
0.630627
f76195ae533709d984434f7e0567c00f8eaf74fc
193
exs
Elixir
test/adel_web/controllers/page_controller_test.exs
zentetsukenz/adel
08854ec56fb6dfe6912abe79ab8aa25ecc3d541a
[ "MIT" ]
null
null
null
test/adel_web/controllers/page_controller_test.exs
zentetsukenz/adel
08854ec56fb6dfe6912abe79ab8aa25ecc3d541a
[ "MIT" ]
null
null
null
test/adel_web/controllers/page_controller_test.exs
zentetsukenz/adel
08854ec56fb6dfe6912abe79ab8aa25ecc3d541a
[ "MIT" ]
null
null
null
defmodule AdelWeb.PageControllerTest do use AdelWeb.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
21.444444
60
0.673575
f761b9678398901766079bfcc021581b4f1c6c0d
83
exs
Elixir
test/test_helper.exs
fremantle-capital/ex_bitfinex
9de76632ce54f6f1ed0d93ec45f17fbc5095b7ab
[ "MIT" ]
560
2018-06-18T20:56:54.000Z
2022-03-23T00:30:50.000Z
test/test_helper.exs
fremantle-capital/ex_bitfinex
9de76632ce54f6f1ed0d93ec45f17fbc5095b7ab
[ "MIT" ]
133
2019-09-13T17:46:59.000Z
2022-03-01T13:37:10.000Z
test/test_helper.exs
fremantle-capital/ex_bitfinex
9de76632ce54f6f1ed0d93ec45f17fbc5095b7ab
[ "MIT" ]
43
2018-06-09T09:54:51.000Z
2021-03-07T07:35:17.000Z
ExUnit.configure(formatters: [ExUnit.CLIFormatter, ExUnitNotifier]) ExUnit.start()
27.666667
67
0.819277
f761cd28544afe08c0e53ea8220d382912f2792d
5,055
exs
Elixir
priv/templates/ptr.gen.html/controller_test.exs
francocatena/ptr
4c8a960cdcb1c8523334fcc0cddba6b7fb3b3e60
[ "MIT" ]
null
null
null
priv/templates/ptr.gen.html/controller_test.exs
francocatena/ptr
4c8a960cdcb1c8523334fcc0cddba6b7fb3b3e60
[ "MIT" ]
2
2021-03-09T01:59:47.000Z
2022-02-10T17:08:54.000Z
priv/templates/ptr.gen.html/controller_test.exs
francocatena/ptr
4c8a960cdcb1c8523334fcc0cddba6b7fb3b3e60
[ "MIT" ]
null
null
null
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>ControllerTest do use <%= inspect context.web_module %>.ConnCase use <%= inspect context.base_module %>.Support.LoginHelper import <%= inspect context.base_module %>.Support.FixtureHelper @create_attrs <%= inspect schema.params.create %> @update_attrs <%= inspect schema.params.update %> @invalid_attrs <%= inspect for {key, _} <- schema.params.create, into: %{}, do: {key, nil} %> describe "unauthorized access" do test "requires user authentication on all actions", %{conn: conn} do Enum.each([ get(conn, Routes.<%= schema.route_helper %>_path(conn, :index)), get(conn, Routes.<%= schema.route_helper %>_path(conn, :new)), post(conn, Routes.<%= schema.route_helper %>_path(conn, :create, %{})), get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, "123")), get(conn, Routes.<%= schema.route_helper %>_path(conn, :edit, "123")), put(conn, Routes.<%= schema.route_helper %>_path(conn, :update, "123", %{})), delete(conn, Routes.<%= schema.route_helper %>_path(conn, :delete, "123")) ], fn conn -> assert html_response(conn, 302) assert conn.halted end) end end describe "index" do setup [:create_<%= schema.singular %>] @tag login_as: "[email protected]" test "lists all <%= schema.plural %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do conn = get conn, Routes.<%= schema.route_helper %>_path(conn, :index) response = html_response(conn, 200) assert response =~ "<%= schema.human_plural %>" assert response =~ <%= schema.singular %>.<%= schema.types |> Enum.at(0) |> Tuple.to_list() |> hd() %> end end describe "empty index" do @tag login_as: "[email protected]" test "lists no <%= schema.plural %>", %{conn: conn} do conn = get conn, Routes.<%= schema.route_helper %>_path(conn, :index) assert html_response(conn, 200) =~ "you have no <%= schema.plural %>" end end describe "new <%= schema.singular %>" do @tag login_as: "[email protected]" test "renders form", %{conn: conn} do conn = get conn, Routes.<%= schema.route_helper %>_path(conn, :new) assert html_response(conn, 200) =~ "New <%= schema.singular %>" end end describe "create <%= schema.singular %>" do @tag login_as: "[email protected]" test "redirects to show when data is valid", %{conn: conn} do conn = post conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @create_attrs assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, id) end @tag login_as: "[email protected]" test "renders errors when data is invalid", %{conn: conn} do conn = post conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @invalid_attrs assert html_response(conn, 200) =~ "New <%= schema.singular %>" end end describe "edit <%= schema.singular %>" do setup [:create_<%= schema.singular %>] @tag login_as: "[email protected]" test "renders form for editing chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do conn = get conn, Routes.<%= schema.route_helper %>_path(conn, :edit, <%= schema.singular %>) assert html_response(conn, 200) =~ "Edit <%= schema.singular %>" end end describe "update <%= schema.singular %>" do setup [:create_<%= schema.singular %>] @tag login_as: "[email protected]" test "redirects when data is valid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do conn = put conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @update_attrs assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>) end @tag login_as: "[email protected]" test "renders errors when data is invalid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do conn = put conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @invalid_attrs assert html_response(conn, 200) =~ "Edit <%= schema.singular %>" end end describe "delete <%= schema.singular %>" do setup [:create_<%= schema.singular %>] @tag login_as: "[email protected]" test "deletes chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do conn = delete conn, Routes.<%= schema.route_helper %>_path(conn, :delete, <%= schema.singular %>) assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :index) end end defp create_<%= schema.singular %>(_) do {:ok, <%= schema.singular %>, _} = fixture(:<%= schema.singular %>) {:ok, <%= schema.singular %>: <%= schema.singular %>} end end
41.434426
140
0.622156
f76201577607d160c4048741a8062ff212dd175e
2,078
exs
Elixir
priv/merge_tags.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
16
2019-04-04T06:33:33.000Z
2021-08-16T19:34:31.000Z
priv/merge_tags.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
294
2019-02-10T11:10:27.000Z
2022-03-30T04:52:53.000Z
priv/merge_tags.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
10
2019-02-10T10:39:24.000Z
2021-07-06T11:46:05.000Z
alias Cforum.Repo alias Cforum.Tags.Synonym import Ecto.Query defmodule Tag do use CforumWeb, :model alias Ecto.Changeset @primary_key {:tag_id, :id, autogenerate: true} schema "tags" do field(:tag_name, :string) field(:slug, :string) field(:num_messages, :integer) field(:suggest, :boolean) field(:forum_id, :id) has_many(:synonyms, Synonym, foreign_key: :tag_id) end def merge_tags(tags) do [orig_tag | rest] = tags unknown_synonyms = rest |> Enum.flat_map(& &1.synonyms) |> Enum.filter(fn synonym -> Enum.find(orig_tag.synonyms, &(&1.synonym != synonym.synonym)) == nil end) |> Enum.uniq_by(& &1.synonym) |> Enum.map(& &1.tag_synonym_id) if unknown_synonyms != [] do from(syn in Synonym, where: syn.tag_synonym_id in ^unknown_synonyms) |> Repo.update_all(set: [tag_id: orig_tag.tag_id]) end tag_ids = Enum.map(rest, & &1.tag_id) from(m in Cforum.MessagesTags.MessageTag, where: m.tag_id in ^tag_ids) |> Repo.update_all(set: [tag_id: orig_tag.tag_id]) from(m in Tag, where: m.tag_id in ^tag_ids) |> Repo.delete_all() end end Repo.transaction(fn -> tags = from(t in Tag, order_by: [asc: t.forum_id, asc: t.tag_id], preload: [:synonyms]) |> Repo.all() |> Enum.reduce(%{}, fn tag, by_name -> Map.update(by_name, tag.tag_name, [tag], &(&1 ++ [tag])) end) |> Enum.filter(fn {_key, values} -> length(values) > 1 end) |> Enum.each(fn {_key, values} -> Tag.merge_tags(values) end) # next make synonyms unique synonyms = from(syn in Synonym, group_by: fragment("tag_id, lower(synonym)"), having: fragment("count(lower(synonym)) > 1"), select: {syn.tag_id, fragment("lower(synonym)")} ) |> Repo.all() |> Enum.each(fn {tag_id, syn_val} -> from(syn in Synonym, where: syn.tag_id == ^tag_id and syn.synonym == ^syn_val, order_by: [asc: :tag_synonym_id], offset: 1 ) |> Repo.all() |> Enum.each(&Repo.delete/1) end) {:ok, nil} end)
26.641026
104
0.615977
f76268be9539f23ca0a095e85ed6eae12598e57b
876
ex
Elixir
lib/polaris/application.ex
mayel/polaris
9b610f83883d009847a72452635d18427f1c7872
[ "Apache-2.0" ]
2
2020-05-02T00:16:35.000Z
2020-06-18T11:43:17.000Z
lib/polaris/application.ex
mayel/polaris
9b610f83883d009847a72452635d18427f1c7872
[ "Apache-2.0" ]
2
2021-03-10T10:35:32.000Z
2021-05-11T06:13:28.000Z
lib/polaris/application.ex
mayel/polaris
9b610f83883d009847a72452635d18427f1c7872
[ "Apache-2.0" ]
2
2020-12-03T10:41:14.000Z
2022-01-17T20:22:50.000Z
defmodule Polaris.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Start the endpoint when the application starts PolarisWeb.Endpoint # Starts a worker by calling: Polaris.Worker.start_link(arg) # {Polaris.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Polaris.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do PolarisWeb.Endpoint.config_change(changed, removed) :ok end end
29.2
66
0.72032
f7626a5920643706b8e453e8efc3db38b0bda143
1,113
ex
Elixir
lib/example_profile_read.ex
FelixW0lf/element-parsers
cced91b2299a3c9e9dbe8cd7b9863d4f64adaf19
[ "MIT" ]
1
2021-11-10T18:06:59.000Z
2021-11-10T18:06:59.000Z
lib/example_profile_read.ex
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
lib/example_profile_read.ex
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
defmodule Parser do use Platform.Parsing.Behaviour require Logger # Example parser for reading values from device profile # # A profile has a "technical name" and each field has its own "technical name". # These are needed here, NOT the display name! # # Changelog: # 2019-09-30 [jb]: Initial implementation def preloads do [device: [profile_data: [:profile]]] end def parse(<<value::16>>, %{meta: %{frame_port: 42}} = meta) do factor = get(meta, [:device, :fields, :my_profile, :my_field], 1) %{ value: value * factor, } end def parse(payload, meta) do Logger.warn("Could not parse payload #{inspect payload} with frame_port #{inspect get_in(meta, [:meta, :frame_port])}") [] end def tests() do [ { # No profile given, default factor =1 will be used. :parse_hex, "1337", %{meta: %{frame_port: 42}}, %{value: 4919}, }, { # Profile has factor value =2. :parse_hex, "1337", %{meta: %{frame_port: 42}, device: %{fields: %{my_profile: %{my_field: 2}}}}, %{value: 9838}, }, ] end end
27.146341
123
0.605571
f7628904045e1be456dea59c22f8d90b6364223d
20,860
exs
Elixir
apps/api_web/test/api_web/controllers/stop_controller_test.exs
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
null
null
null
apps/api_web/test/api_web/controllers/stop_controller_test.exs
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
null
null
null
apps/api_web/test/api_web/controllers/stop_controller_test.exs
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
null
null
null
defmodule ApiWeb.StopControllerTest do use ApiWeb.ConnCase alias Model.{Facility, Stop, Transfer} setup %{conn: conn} do State.Stop.new_state([]) {:ok, conn: put_req_header(conn, "accept", "application/json")} end describe "index" do test "lists all entries", %{conn: conn} do conn = get(conn, stop_path(conn, :index)) assert json_response(conn, 200)["data"] == [] end test "conforms to swagger response", %{swagger_schema: schema, conn: conn} do response = get(conn, stop_path(conn, :index)) assert validate_resp_schema(response, schema, "Stops") end test "can sort by distance to location", %{conn: base_conn} do stop1 = %Stop{id: "1", latitude: 1, longitude: 1} stop2 = %Stop{id: "3", latitude: 1, longitude: 3} stop3 = %Stop{id: "2", latitude: 1, longitude: 2} State.Stop.new_state([stop1, stop2, stop3]) conn = get(base_conn, stop_path(base_conn, :index), %{ "latitude" => "0", "longitude" => "0", "radius" => "10", "sort" => "distance" }) assert [ %{"attributes" => %{"longitude" => 1}}, %{"attributes" => %{"longitude" => 2}}, %{"attributes" => %{"longitude" => 3}} ] = json_response(conn, 200)["data"] conn = get(base_conn, stop_path(base_conn, :index), %{ "latitude" => "0", "longitude" => "0", "radius" => "10", "sort" => "-distance" }) assert [ %{"attributes" => %{"longitude" => 3}}, %{"attributes" => %{"longitude" => 2}}, %{"attributes" => %{"longitude" => 1}} ] = json_response(conn, 200)["data"] end test "can sort by distance to location with filter[latitude] or just latitude", %{ conn: base_conn } do stop1 = %Stop{id: "1", latitude: 1, longitude: 1} stop2 = %Stop{id: "3", latitude: 1, longitude: 3} stop3 = %Stop{id: "2", latitude: 1, longitude: 2} State.Stop.new_state([stop1, stop2, stop3]) conn = get(base_conn, stop_path(base_conn, :index), %{ "filter" => %{"latitude" => "0", "longitude" => "0"}, "radius" => "10", "sort" => "distance" }) assert [ %{"attributes" => %{"longitude" => 1}}, %{"attributes" => %{"longitude" => 2}}, %{"attributes" => %{"longitude" => 3}} ] = json_response(conn, 200)["data"] conn = get(base_conn, stop_path(base_conn, :index), %{ "latitude" => "0", "filter" => %{"longitude" => "0"}, "radius" => "10", "sort" => "distance" }) assert [ %{"attributes" => %{"longitude" => 1}}, %{"attributes" => %{"longitude" => 2}}, %{"attributes" => %{"longitude" => 3}} ] = json_response(conn, 200)["data"] end test "returns 400 if sort=distance is specified and latitude or longitude is missing", %{ conn: base_conn } do conn = get(base_conn, stop_path(base_conn, :index), %{ "latitude" => "0", "radius" => "10", "sort" => "distance" }) assert conn.status == 400 end test "can search by location", %{conn: base_conn} do stop = %Stop{id: "1", latitude: 1, longitude: 2} State.Stop.new_state([stop]) conn = get(base_conn, stop_path(base_conn, :index), %{"latitude" => "1", "longitude" => "2"}) assert List.first(json_response(conn, 200)["data"])["id"] == "1" # too far for default conn = get(base_conn, stop_path(base_conn, :index), %{"latitude" => "2", "longitude" => "2"}) assert json_response(conn, 200)["data"] == [] # set the radius conn = get(base_conn, stop_path(base_conn, :index), %{ "latitude" => "2", "longitude" => "2", "radius" => "1" }) assert List.first(json_response(conn, 200)["data"])["id"] == "1" end test "can search by ids", %{conn: conn} do stops = for id <- ~w(one two three) do %Stop{id: id} end State.Stop.new_state(stops) conn = get(conn, stop_path(conn, :index), %{"id" => "one,three"}) ids = for data <- json_response(conn, 200)["data"] do data["id"] end assert Enum.sort(ids) == ~w(one three) end test "can search by route and route type", %{conn: base_conn} do # set up the data for StopsOnRoute set_up_stops_on_route() conn = get(base_conn, stop_path(base_conn, :index), %{"route" => "route"}) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] conn = get(base_conn, stop_path(base_conn, :index), %{"route" => "route,other"}) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["2", "1"] conn = get(base_conn, stop_path(base_conn, :index), %{"route" => "other route"}) assert json_response(conn, 200)["data"] == [] # route type query conn = get(base_conn, stop_path(base_conn, :index), %{"route_type" => "2,3"}) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] conn = get(base_conn, stop_path(base_conn, :index), %{"route_type" => "3"}) assert json_response(conn, 200)["data"] == [] # route type query combined with lat/long query conn = get(base_conn, stop_path(base_conn, :index), %{ "route_type" => "2", "latitude" => "1", "longitude" => "2" }) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] # null intersection between route type and lat/long queries conn = get(base_conn, stop_path(base_conn, :index), %{ "route_type" => "4", "latitude" => "1", "longitude" => "2" }) assert json_response(conn, 200)["data"] == [] end test "keeps stops in route order", %{conn: conn} do for _ <- 0..10 do stop = %Stop{id: random_id()} stop2 = %Stop{id: random_id()} State.Stop.new_state([stop, stop2]) State.Route.new_state([%Model.Route{id: "route"}]) State.Trip.new_state([%Model.Trip{id: "trip", route_id: "route"}]) State.Schedule.new_state([ %Model.Schedule{trip_id: "trip", stop_id: stop.id, stop_sequence: 1}, %Model.Schedule{trip_id: "trip", stop_id: stop2.id, stop_sequence: 2} ]) State.StopsOnRoute.update!() conn = get(conn, stop_path(conn, :index), %{"filter" => %{"route" => "route"}}) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == [stop.id, stop2.id] end end test "can include a route we're filtering on", %{conn: conn} do set_up_stops_on_route() response = conn |> get( stop_path(conn, :index, %{"filter" => %{"route" => "route"}, "include" => "route"}) ) |> json_response(200) assert %{ "type" => "route", "id" => "route" } = List.first(response["included"]) end test "can filter on route and direction_id", %{conn: base_conn} do set_up_stops_on_route() params = %{"filter" => %{"route" => "route,other", "direction_id" => "1"}} conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] params = put_in(params, ["filter", "direction_id"], "0") conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["2"] end test "can filter routes by date", %{conn: base_conn} do today = Parse.Time.service_date() future = %{today | year: today.year + 1} bad_date = %{today | year: today.year - 1} stop = %Stop{id: "1"} service = %Model.Service{ id: "service", start_date: today, end_date: today, added_dates: [today] } route = %Model.Route{id: "route", type: 2} trip = %Model.Trip{id: "trip", route_id: "route", service_id: "service"} schedule = %Model.Schedule{trip_id: "trip", stop_id: "1"} feed = %Model.Feed{start_date: bad_date, end_date: future} State.Service.new_state([service]) State.Trip.reset_gather() State.Stop.new_state([stop]) State.Route.new_state([route]) State.Trip.new_state([trip]) State.Schedule.new_state([schedule]) State.RoutesPatternsAtStop.update!() State.StopsOnRoute.update!() State.Feed.new_state(feed) today_iso = Date.to_iso8601(today) bad_date_iso = Date.to_iso8601(bad_date) params = %{"filter" => %{"route" => "route", "date" => today_iso}} conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] params = put_in(params, ["filter", "date"], bad_date_iso) conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == [] end test "can filter routes by service", %{conn: base_conn} do today = Parse.Time.service_date() stop = %Stop{id: "1"} service = %Model.Service{id: "service", start_date: today, end_date: today} route = %Model.Route{id: "route", type: 2} trip = %Model.Trip{id: "trip", route_id: "route", service_id: "service"} schedule = %Model.Schedule{trip_id: "trip", stop_id: "1"} State.Service.new_state([service]) State.Trip.reset_gather() State.Stop.new_state([stop]) State.Route.new_state([route]) State.Trip.new_state([trip]) State.Schedule.new_state([schedule]) State.RoutesPatternsAtStop.update!() State.StopsOnRoute.update!() params = %{"filter" => %{"route" => "route", "service" => "service"}} conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] params = put_in(params, ["filter", "service"], "bad_service") conn = get(base_conn, stop_path(base_conn, :index, params)) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == [] end test "can filter by location_type", %{conn: base_conn} do stop = %Stop{id: 1, location_type: 0} State.Stop.new_state([stop]) conn = get(base_conn, stop_path(base_conn, :index), %{ "location_type" => "1,2" }) assert json_response(conn, 200)["data"] == [] conn = get(base_conn, stop_path(base_conn, :index), %{ "location_type" => "0" }) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] end test "can be paginated and sorted", %{conn: base_conn} do set_up_stops_on_route() opts = %{"page" => %{"offset" => 1, "limit" => 1}} conn = get(base_conn, stop_path(base_conn, :index, Map.merge(opts, %{"sort" => "id"}))) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["2"] conn = get(base_conn, stop_path(base_conn, :index, Map.merge(opts, %{"sort" => "-id"}))) assert Enum.map(json_response(conn, 200)["data"], & &1["id"]) == ["1"] end test "can include facilities", %{conn: conn} do facility = %Facility{id: "6", stop_id: "stop"} State.Facility.new_state([facility]) stop = %Stop{id: "stop"} State.Stop.new_state([stop]) conn = get(conn, stop_path(conn, :index), %{include: "facilities"}) response = json_response(conn, 200) [stop] = response["data"] assert [%{"type" => "facility", "id" => "6"}] = stop["relationships"]["facilities"]["data"] assert [%{"type" => "facility", "id" => "6"}] = response["included"] end test "can filter by ID with legacy stop ID translation", %{conn: conn} do State.Stop.new_state([%Stop{id: "place-nubn"}, %Stop{id: "other"}]) response = conn |> assign(:api_version, "2020-05-01") |> get(stop_path(conn, :index), %{"id" => "place-dudly,other"}) |> json_response(200) assert Enum.map(response["data"], & &1["id"]) == ~w(place-nubn other) end end describe "show" do test "shows chosen resource", %{conn: conn} do stop = %Stop{id: "1"} State.Stop.new_state([stop]) conn = get(conn, stop_path(conn, :show, stop)) assert json_response(conn, 200)["data"]["id"] == stop.id end test "does not allow filtering", %{conn: conn} do stop = %Stop{id: "1"} State.Stop.new_state([stop]) conn = get(conn, stop_path(conn, :show, stop.id, %{"filter[route]" => "1"})) assert json_response(conn, 400) end test "does not crash when given weird input", %{conn: conn} do conn = get(conn, stop_path(conn, :show, "%")) assert json_response(conn, 404) end test "conforms to swagger response", %{swagger_schema: schema, conn: conn} do stop = %Stop{ id: "1", latitude: 42.3605, longitude: -71.0596, name: "Boston", wheelchair_boarding: 1, parent_station: "2" } parent_station = %Stop{id: "2"} State.Stop.new_state([stop, parent_station]) response = get(conn, stop_path(conn, :show, "1")) assert validate_resp_schema(response, schema, "Stop") end test "can include a parent stop", %{conn: conn} do parent = %Stop{id: "1"} child = %Stop{id: "2", parent_station: "1"} State.Stop.new_state([parent, child]) conn = get(conn, stop_path(conn, :show, child), %{include: "parent_station"}) response = json_response(conn, 200) assert response["data"]["relationships"]["parent_station"]["data"]["id"] == "1" [included] = response["included"] assert included["id"] == "1" end test "can include child stops", %{conn: conn} do parent = %Stop{id: "1"} child = %Stop{id: "2", parent_station: "1"} State.Stop.new_state([parent, child]) conn = get(conn, stop_path(conn, :show, parent)) response = json_response(conn, 200) # no data included refute response["data"]["relationships"]["child_stops"]["data"] conn = get(conn, stop_path(conn, :show, parent), %{include: "child_stops"}) response = json_response(conn, 200) assert response["data"]["relationships"]["child_stops"]["data"] == [ %{"type" => "stop", "id" => "2"} ] [included] = response["included"] assert included["id"] == "2" end test "can include recommended transfers", %{conn: conn} do from = %Stop{id: "1"} to = %Stop{id: "2"} transfer = %Transfer{from_stop_id: "1", to_stop_id: "2", transfer_type: 0} State.Stop.new_state([from, to]) State.Transfer.new_state([transfer]) conn = get(conn, stop_path(conn, :show, from)) response = json_response(conn, 200) refute response["data"]["relationships"]["recommended_transfers"]["data"] conn = get(conn, stop_path(conn, :show, from), %{include: "recommended_transfers"}) response = json_response(conn, 200) assert response["data"]["relationships"]["recommended_transfers"]["data"] == [ %{"type" => "stop", "id" => "2"} ] [included] = response["included"] assert included["id"] == "2" end test "can include facilities", %{conn: conn} do facility = %Facility{id: "6", stop_id: "stop"} State.Facility.new_state([facility]) stop = %Stop{id: "stop"} State.Stop.new_state([stop]) conn = get(conn, stop_path(conn, :show, stop), %{include: "facilities"}) response = json_response(conn, 200) assert [%{"type" => "facility", "id" => "6"}] = response["data"]["relationships"]["facilities"]["data"] assert [%{"type" => "facility", "id" => "6"}] = response["included"] end test "can filter fields", %{conn: conn} do stop = %Stop{id: "1"} State.Stop.new_state([stop]) conn = get(conn, stop_path(conn, :show, stop, %{"fields[stop]" => ""})) assert json_response(conn, 200)["data"]["attributes"] == %{} end test "has zone relationship in response", %{conn: conn} do stop1 = %Stop{id: "1", zone_id: "CR-zone-6"} stop2 = %Stop{id: "2", zone_id: nil} State.Stop.new_state([stop1, stop2]) conn = get(conn, stop_path(conn, :show, stop1)) response = json_response(conn, 200) assert response["data"]["relationships"]["zone"]["data"] == %{ "id" => "CR-zone-6", "type" => "zone" } conn = get(conn, stop_path(conn, :show, stop2)) response = json_response(conn, 200) refute response["data"]["relationships"]["zone"]["data"] end test "cannot include zone", %{conn: conn} do stop = %Stop{id: "1", zone_id: "CR-zone-6"} State.Stop.new_state([stop]) response = get(conn, stop_path(conn, :show, stop, %{"include" => "zone"})) assert json_response(response, 400) end test "does not show resource and returns JSON-API error document when id is nonexistent", %{ conn: conn, swagger_schema: swagger_shema } do conn = get(conn, stop_path(conn, :show, -1)) assert json_response(conn, 404) assert validate_resp_schema(conn, swagger_shema, "NotFound") end test "returns CORS headers", %{conn: conn} do origin = "https://cors.origin" conn = conn |> put_req_header("origin", origin) |> get(stop_path(conn, :index)) assert json_response(conn, 200) refute get_resp_header(conn, "access-control-allow-origin") == [] end test "translates stop IDs that were renamed", %{conn: conn} do State.Stop.new_state([%Stop{id: "place-nubn"}]) response = conn |> assign(:api_version, "2020-05-01") |> get(stop_path(conn, :show, "place-dudly")) |> json_response(200) assert response["data"]["id"] == "place-nubn" response = conn |> assign(:api_version, "2020-XX-XX") |> get(stop_path(conn, :show, "place-dudly")) |> json_response(404) assert response["errors"] # ensure this also works *before* the transition has occurred State.Stop.new_state([%Stop{id: "place-dudly"}]) response = conn |> assign(:api_version, "2020-05-01") |> get(stop_path(conn, :show, "place-dudly")) |> json_response(200) assert response["data"]["id"] == "place-dudly" response = conn |> assign(:api_version, "2020-XX-XX") |> get(stop_path(conn, :show, "place-dudly")) |> json_response(200) assert response["data"]["id"] == "place-dudly" end test "doesn't translate stop IDs that weren't renamed", %{conn: conn} do State.Stop.new_state([%Stop{id: "Alewife-01"}, %Stop{id: "Alewife-02"}]) response = conn |> assign(:api_version, "2018-07-23") |> get(stop_path(conn, :show, "70061")) |> json_response(404) assert response["errors"] end end test "state_module/0" do assert State.Stop.Cache == ApiWeb.StopController.state_module() end describe "swagger_path" do test "swagger_path_index generates docs for GET /stops" do assert %{"/stops" => %{"get" => %{"responses" => %{"200" => %{}}}}} = ApiWeb.StopController.swagger_path_index(%{}) end test "swagger_path_show generates docs for GET /stops/{id}" do assert %{ "/stops/{id}" => %{ "get" => %{ "responses" => %{ "200" => %{}, "404" => %{} } } } } = ApiWeb.StopController.swagger_path_show(%{}) end end defp random_id do System.unique_integer() |> Integer.to_string() end defp set_up_stops_on_route do stop = %Stop{id: "1", latitude: 1, longitude: 2} stop2 = %Stop{id: "2"} State.Stop.new_state([stop, stop2]) State.Route.new_state([%Model.Route{id: "route", type: 2}, %Model.Route{id: "other", type: 4}]) State.Trip.new_state([ %Model.Trip{id: "trip", route_id: "route", direction_id: 1}, %Model.Trip{id: "other", route_id: "other", direction_id: 0} ]) State.Schedule.new_state([ %Model.Schedule{trip_id: "trip", stop_id: "1", route_id: "route"}, %Model.Schedule{trip_id: "other", stop_id: "2", route_id: "other"} ]) State.RoutesPatternsAtStop.update!() State.StopsOnRoute.update!() end end
33.483146
99
0.557143
f762af800aefd9fb0f40e3d6d0b5a0e20dec6ed3
30,702
ex
Elixir
lib/trash/repo.ex
newaperio/trash
ad7f82dab736c8b4e926888f8f09fce078b289ac
[ "MIT" ]
1
2022-03-18T15:26:07.000Z
2022-03-18T15:26:07.000Z
lib/trash/repo.ex
newaperio/trash
ad7f82dab736c8b4e926888f8f09fce078b289ac
[ "MIT" ]
null
null
null
lib/trash/repo.ex
newaperio/trash
ad7f82dab736c8b4e926888f8f09fce078b289ac
[ "MIT" ]
null
null
null
defmodule Trash.Repo do @moduledoc """ Provides functions for discarding and keeping records and querying for them via `Ecto.Repo` functions. """ require Ecto.Query alias Ecto.Query alias Ecto.Queryable alias Ecto.Changeset alias Trash.Query, as: TrashQuery @doc """ Imports functions from `Trash.Repo`. It's not required to `use` this module in order to use `Trash`. Doing so will import shorthand functions into your app's `Repo` module with the repo implicitly passed. It's a bit more convenient, but the functions are public on `Trash.Repo`, so if preferred they can be called directly. ``` # Shorthand with `use` MyRepo.all_discarded(Post) # Long form without Trash.Repo.all_discarded(Post, [], MyRepo) ``` ## Options - `repo` - A module reference to an `Ecto.Repo`; raises `ArgumentError` if missing ## Examples defmodule MyApp.Repo use Ecto.Schema use Trash.Schema, repo: __MODULE__ end """ # credo:disable-for-this-file Credo.Check.Refactor.LongQuoteBlocks # credo:disable-for-this-file Credo.Check.Consistency.ParameterPatternMatching @spec __using__(opts :: list()) :: Macro.t() defmacro __using__(opts) do quote do import unquote(__MODULE__) @__trash_repo__ unquote(compile_config(opts)) @doc """ Fetches all entries matching the given query that have been discarded. ## Examples iex> MyRepo.all_discarded(Post) [%Post{ title: "Hello World", discarded_at: %DateTime{}, discarded?: nil }] """ @spec all_discarded( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: [Ecto.Schema.t()] def all_discarded(queryable, opts \\ []) do all_discarded(queryable, opts, @__trash_repo__) end @doc """ Fetches all entries matching the given query that have been kept. ## Examples iex> MyRepo.all_kept(Post) [%Post{title: "Hello World", discarded_at: nil, discarded?: nil}] """ @spec all_kept( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: [Ecto.Schema.t()] def all_kept(queryable, opts \\ []) do all_kept(queryable, opts, @__trash_repo__) end @doc """ Updates a record as discarded. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `DateTime.utc_now/1`. It calls `repo.update/2` to finalize the changes. It returns `{:ok, struct}` if the struct has been successfully updated or `{:error, changeset}` if there was an error. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> MyRepo.discard() {:ok, %Post{title: "[Archived] Hello, world", discarded_at: %DateTime{}}} """ @spec discard(changeset_or_schema :: Changeset.t() | Ecto.Schema.t()) :: {:ok, Ecto.Schema.t()} | {:error, Changeset.t()} def discard(changeset = %Changeset{}) do discard(changeset, @__trash_repo__) end def discard(%{__struct__: _} = struct) do discard(struct, @__trash_repo__) end @doc """ Updates a record as discarded. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `DateTime.utc_now/1`. It calls `repo.update/2` to finalize the changes. Raises `Ecto.InvalidChangesetError` if the changeset is invalid. Note: since an `Ecto.Schema` struct can be passed which generates a bare changeset, this will never raise when given a struct. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> MyRepo.discard! %Post{title: "[Archived] Hello, world", discarded_at: %DateTime{}} iex> Post.changeset(post, %{}) |> MyRepo.discard! ** (Ecto.InvalidChangesetError) """ @spec discard!(changeset_or_schema :: Changeset.t() | Ecto.Schema.t()) :: Ecto.Schema.t() def discard!(changeset = %Changeset{}) do discard!(changeset, @__trash_repo__) end def discard!(%{__struct__: _} = struct) do discard!(struct, @__trash_repo__) end @doc """ Checks if there exists an entry that matches the given query that has been discarded. Returns a boolean. ## Examples iex> MyRepo.discarded?(post) true """ @spec discarded?( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: boolean def discarded?(queryable, opts \\ []) do discarded?(queryable, opts, @__trash_repo__) end @doc """ Fetches a single discarded result where the primary key matches the given `id`. Returns `nil` if no result was found. ## Examples iex> MyRepo.get_discarded(Post) %Post{ title: "Hello World", discarded_at: %DateTime{}, discarded?: nil } """ @spec get_discarded( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_discarded(queryable, id, opts \\ []) do get_discarded(queryable, id, opts, @__trash_repo__) end @doc """ Fetches a single discarded result where the primary key matches the given `id`. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.get_discarded!(Post, 1) %Post{ title: "Hello World", discarded_at: %DateTime{}, discarded?: nil } iex> MyRepo.get_discarded!(Post, 2) ** (Ecto.NoResultsError) """ @spec get_discarded!( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_discarded!(queryable, id, opts \\ []) do get_discarded!(queryable, id, opts, @__trash_repo__) end @doc """ Fetches a single discarded result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> MyRepo.get_discarded_by(Post, [title: "Hello World"]) %Post{title: "Hello World", discarded_at: %DateTime{}} """ @spec get_discarded_by( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_discarded_by(queryable, clauses, opts \\ []) do get_discarded_by(queryable, clauses, opts, @__trash_repo__) end @doc """ Fetches a single discarded result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.get_discarded_by!(Post, [title: "Hello World"]) %Post{title: "Hello World", discarded_at: %DateTime{}} iex> MyRepo.get_discarded_by!(Post, [title: "Unwritten"]) ** (Ecto.NoResultsError) """ @spec get_discarded_by!( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() def get_discarded_by!(queryable, clauses, opts \\ []) do get_discarded_by!(queryable, clauses, opts, @__trash_repo__) end @doc """ Fetches a single kept result where the primary key matches the given `id`. Returns `nil` if no result was found. ## Examples iex> MyRepo.get_kept(Post, 1) %Post{title: "Hello World", discarded_at: nil} """ @spec get_kept( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_kept(queryable, id, opts \\ []) do get_kept(queryable, id, opts, @__trash_repo__) end @doc """ Fetches a single kept result where the primary key matches the given `id`. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.get_kept!(Post, 1) %Post{title: "Hello World", discarded_at: nil} iex> MyRepo.get_kept!(Post, 2) ** (Ecto.NoResultsError) """ @spec get_kept!( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_kept!(queryable, id, opts \\ []) do get_kept!(queryable, id, opts, @__trash_repo__) end @doc """ Fetches a single kept result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> MyRepo.get_kept_by(Post, title: "Hello World") %Post{title: "Hello World", discarded_at: nil} """ @spec get_kept_by( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def get_kept_by(queryable, clauses, opts \\ []) do get_kept_by(queryable, clauses, opts, @__trash_repo__) end @doc """ Fetches a single kept result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.get_kept_by!(Post, title: "Hello World") %Post{title: "Hello World", discarded_at: %DateTime{}} iex> MyRepo.get_kept_by!(Post, title: "Not Written") ** (Ecto.NoResultsError) """ @spec get_kept_by!( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() def get_kept_by!(queryable, clauses, opts \\ []) do get_kept_by!(queryable, clauses, opts, @__trash_repo__) end @doc """ Checks if there exists an entry that matches the given query that has been kept. Returns a boolean. ## Examples iex> MyRepo.kept?(post) true """ @spec kept?( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: boolean def kept?(queryable, opts \\ []) do kept?(queryable, opts, @__trash_repo__) end @doc """ Fetches a single discarded result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> MyRepo.one_discarded(Post) %Post{title: "Hello World", discarded_at: %DateTime{}} """ @spec one_discarded( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def one_discarded(queryable, opts \\ []) do one_discarded(queryable, opts, @__trash_repo__) end @doc """ Fetches a single discarded result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.one_discarded!(Post) %Post{title: "Hello World", discarded_at: %DateTime{}} iex> MyRepo.one_discarded!(Post) ** (Ecto.NoResultsError) """ @spec one_discarded!( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() def one_discarded!(queryable, opts \\ []) do one_discarded!(queryable, opts, @__trash_repo__) end @doc """ Fetches a single kept result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> MyRepo.one_kept(Post) %Post{title: "Hello World", discarded_at: nil} """ @spec one_kept( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil def one_kept(queryable, opts \\ []) do one_kept(queryable, opts, @__trash_repo__) end @doc """ Fetches a single kept result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> MyRepo.one_kept!(Post) %Post{title: "Hello World", discarded_at: nil} iex> MyRepo.one_kept!(Post) ** (Ecto.NoResultsError) """ @spec one_kept!( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() def one_kept!(queryable, opts \\ []) do one_kept!(queryable, opts, @__trash_repo__) end @doc """ Updates a record as kept. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `nil`. It calls `repo.update/2` to finalize the changes. It returns `{:ok, struct}` if the struct has been successfully updated or `{:error, changeset}` if there was an error. ## Examples iex> Post.changeset(post, %{title: "Hello, world"}) |> MyRepo.restore() {:ok, %Post{title: "Hello, world", discarded_at: nil}} """ @spec restore(changeset_or_schema :: Changeset.t() | Ecto.Schema.t()) :: {:ok, Ecto.Schema.t()} | {:error, Changeset.t()} def restore(changeset = %Changeset{}) do restore(changeset, @__trash_repo__) end def restore(%{__struct__: _} = struct) do restore(struct, @__trash_repo__) end @doc """ Updates a record as kept. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `nil`. It calls `repo.update/2` to finalize the changes. Raises `Ecto.InvalidChangesetError` if the changeset is invalid. Note: since an `Ecto.Schema` struct can be passed which generates a bare changeset, this will never raise when given a struct. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> MyRepo.restore!() %Post{title: "[Archived] Hello, world", discarded_at: nil} iex> Post.changeset(post, %{}) |> MyRepo.restore!() ** (Ecto.InvalidChangesetError) """ @spec restore!(changeset_or_schema :: Changeset.t() | Ecto.Schema.t()) :: Ecto.Schema.t() def restore!(changeset = %Changeset{}) do restore!(changeset, @__trash_repo__) end def restore!(%{__struct__: _} = struct) do restore!(struct, @__trash_repo__) end end end @doc """ Fetches all entries matching the given query that have been discarded. ## Examples iex> Trash.Repo.all_discarded(Post, [], MyApp.Repo) [%Post{title: "Hello World", discarded_at: %DateTime{}, discarded?: nil}] """ @spec all_discarded( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: [Ecto.Schema.t()] def all_discarded(queryable, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.all(opts) end @doc """ Fetches all entries matching the given query that have been kept. ## Examples iex> Trash.Repo.all_kept(Post, [], MyApp.Repo) [%Post{title: "Hello World", discarded_at: nil, discarded?: nil}] """ @spec all_kept( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: [Ecto.Schema.t()] def all_kept(queryable, opts \\ [], repo) do queryable |> kept_queryable() |> repo.all(opts) end @doc """ Updates a record as discarded. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `DateTime.utc_now/1`. It calls `repo.update/2` to finalize the changes. It returns `{:ok, struct}` if the struct has been successfully updated or `{:error, changeset}` if there was an error. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> Trash.Repo.discard(MyApp.Repo) {:ok, %Post{title: "[Archived] Hello, world", discarded_at: %DateTime{}}} """ @spec discard( changeset_or_schema :: Changeset.t() | Ecto.Schema.t(), repo :: atom ) :: {:ok, Ecto.Schema.t()} | {:error, Changeset.t()} def discard(changeset = %Changeset{}, repo) do changeset |> Changeset.put_change( :discarded_at, DateTime.truncate(DateTime.utc_now(), :second) ) |> repo.update() end def discard(%{__struct__: _} = struct, repo) do struct |> Changeset.change() |> discard(repo) end @doc """ Updates a record as discarded. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `DateTime.utc_now/1`. It calls `repo.update/2` to finalize the changes. Raises `Ecto.InvalidChangesetError` if the changeset is invalid. Note: since an `Ecto.Schema` struct can be passed which generates a bare changeset, this will never raise when given a struct. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> Trash.Repo.discard!(MyApp.Repo) %Post{title: "[Archived] Hello, world", discarded_at: %DateTime{}} iex> Post.changeset(post, %{}) |> Trash.Repo.discard!(MyApp.Repo) ** (Ecto.InvalidChangesetError) """ @spec discard!( changeset_or_schema :: Changeset.t() | Ecto.Schema.t(), repo :: atom ) :: Ecto.Schema.t() def discard!(changeset = %Changeset{}, repo) do case discard(changeset, repo) do {:ok, struct} -> struct {:error, changeset} -> raise Ecto.InvalidChangesetError, action: :discard, changeset: changeset end end def discard!(%{__struct__: _} = struct, repo) do {:ok, struct} = discard(struct, repo) struct end @doc """ Checks if there exists an entry that matches the given query that has been discarded. Returns a boolean. ## Examples iex> Trash.Repo.discarded?(post, [], MyApp.Repo) true """ @spec discarded?( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: boolean def discarded?(queryable, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.exists?(opts) end @doc """ Fetches a single discarded result where the primary key matches the given `id`. Returns `nil` if no result was found. ## Examples iex> Trash.Repo.get_discarded(Post, 1, [], MyApp.Repo) %Post{} """ @spec get_discarded( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_discarded(queryable, id, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.get(id, opts) end @doc """ Fetches a single discarded result where the primary key matches the given `id`. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.get_discarded!(Post, 1, [], MyApp.Repo) %Post{} iex> Trash.Repo.get_discarded!(Post, 2, [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec get_discarded!( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_discarded!(queryable, id, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.get!(id, opts) end @doc """ Fetches a single discarded result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> Trash.Repo.get_discarded_by(Post, [title: "Hello World"], [], MyApp.Repo) %Post{title: "Hello World", discarded_at: %DateTime{}} """ @spec get_discarded_by( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_discarded_by(queryable, clauses, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.get_by(clauses, opts) end @doc """ Fetches a single discarded result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.get_discarded_by!(Post, [title: "Hello World"], [], MyApp.Repo) %Post{title: "Hello World", discarded_at: %DateTime{}} iex> Trash.Repo.get_discarded_by!(Post, [title: "Hello World"], [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec get_discarded_by!( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() def get_discarded_by!(queryable, clauses, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.get_by!(clauses, opts) end @doc """ Fetches a single kept result where the primary key matches the given `id`. Returns `nil` if no result was found. ## Examples iex> Trash.Repo.get_kept(Post, 1, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: nil} """ @spec get_kept( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_kept(queryable, id, opts \\ [], repo) do queryable |> kept_queryable() |> repo.get(id, opts) end @doc """ Fetches a single kept result where the primary key matches the given `id`. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.get_kept!(Post, 1, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: nil} iex> Trash.Repo.get_kept!(Post, 2, [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec get_kept!( queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_kept!(queryable, id, opts \\ [], repo) do queryable |> kept_queryable() |> repo.get!(id, opts) end @doc """ Fetches a single kept result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> Trash.Repo.get_kept_by(Post, title: "Hello World", [], MyApp.Repo) %Post{title: "Hello World", discarded_at: nil} """ @spec get_kept_by( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def get_kept_by(queryable, clauses, opts \\ [], repo) do queryable |> kept_queryable() |> repo.get_by(clauses, opts) end @doc """ Fetches a single kept result from the query. Raises `Ecto.MultipleResultsError` if more than one result. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.get_kept_by!(Post, title: "Hello World", [], MyApp.Repo) %Post{title: "Hello World", discarded_at: %DateTime{}} iex> Trash.Repo.get_kept_by!(Post, title: "Not Written", [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec get_kept_by!( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() def get_kept_by!(queryable, clauses, opts \\ [], repo) do queryable |> kept_queryable() |> repo.get_by!(clauses, opts) end @doc """ Checks if there exists an entry that matches the given query that has been kept. Returns a boolean. ## Examples iex> Trash.Repo.kept?(post, [], MyApp.Repo) true """ @spec kept?( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: boolean def kept?(queryable, opts \\ [], repo) do queryable |> kept_queryable() |> repo.exists?(opts) end @doc """ Fetches a single discarded result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> Trash.Repo.one_discarded(Post, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: %DateTime{}} """ @spec one_discarded( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def one_discarded(queryable, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.one(opts) end @doc """ Fetches a single discarded result from the query. Raises `Ecto.MultipleResultsError` if more than one entry. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.one_discarded!(Post, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: %DateTime{}} iex> Trash.Repo.one_discarded!(Post, [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec one_discarded!( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() def one_discarded!(queryable, opts \\ [], repo) do queryable |> discarded_queryable() |> repo.one!(opts) end @doc """ Fetches a single kept result from the query. Returns `nil` if no result was found or raises `Ecto.MultipleResultsError` if more than one entry. ## Examples iex> Trash.Repo.one_kept(Post, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: nil} """ @spec one_kept( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() | nil def one_kept(queryable, opts \\ [], repo) do queryable |> kept_queryable() |> repo.one(opts) end @doc """ Fetches a single kept result from the query. Raises `Ecto.MultipleResultsError` if more than one entry. Raises `Ecto.NoResultsError` if no result was found. ## Examples iex> Trash.Repo.one_kept!(Post, [], MyApp.Repo) %Post{title: "Hello World", discarded_at: nil} iex> Trash.Repo.one_kept!(Post, [], MyApp.Repo) ** (Ecto.NoResultsError) """ @spec one_kept!( queryable :: Ecto.Queryable.t(), opts :: Keyword.t(), repo :: atom ) :: Ecto.Schema.t() def one_kept!(queryable, opts \\ [], repo) do queryable |> kept_queryable() |> repo.one!(opts) end @doc """ Updates a record as kept. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `nil`. It calls `repo.update/2` to finalize the changes. It returns `{:ok, struct}` if the struct has been successfully updated or `{:error, changeset}` if there was an error. ## Examples iex> Post.changeset(post, %{title: "Hello, world"}) |> Trash.Repo.restore(MyApp.Repo) {:ok, %Post{title: "Hello, world", discarded_at: nil}} """ @spec restore( changeset_or_schema :: Changeset.t() | Ecto.Schema.t(), repo :: atom ) :: {:ok, Ecto.Schema.t()} | {:error, Changeset.t()} def restore(changeset = %Changeset{}, repo) do changeset |> Changeset.put_change(:discarded_at, nil) |> repo.update() end def restore(%{__struct__: _} = struct, repo) do struct |> Changeset.change() |> restore(repo) end @doc """ Updates a record as kept. This takes either an `Ecto.Changeset` or an `Ecto.Schema` struct. If a struct is given a bare changeset is generated first. A change is added to the changeset to set `discarded_at` to `nil`. It calls `repo.update/2` to finalize the changes. Raises `Ecto.InvalidChangesetError` if the changeset is invalid. Note: since an `Ecto.Schema` struct can be passed which generates a bare changeset, this will never raise when given a struct. ## Examples iex> Post.changeset(post, %{title: "[Archived] Hello, world"}) |> Trash.Repo.restore!(MyApp.Repo) %Post{title: "[Archived] Hello, world", discarded_at: nil} iex> Post.changeset(post, %{}) |> Trash.Repo.restore!(MyApp.Repo) ** (Ecto.InvalidChangesetError) """ @spec restore!( changeset_or_schema :: Changeset.t() | Ecto.Schema.t(), repo :: atom ) :: Ecto.Schema.t() def restore!(changeset = %Changeset{}, repo) do case restore(changeset, repo) do {:ok, struct} -> struct {:error, changeset} -> raise Ecto.InvalidChangesetError, action: :restore, changeset: changeset end end def restore!(%{__struct__: _} = struct, repo) do {:ok, struct} = restore(struct, repo) struct end defp compile_config(opts) do case Keyword.fetch(opts, :repo) do {:ok, value} -> value :error -> raise ArgumentError, "missing :repo option on use Trash.Repo" end end defp discarded_queryable(queryable) do queryable |> Queryable.to_query() |> Query.from() |> TrashQuery.where_discarded() end defp kept_queryable(queryable) do queryable |> Queryable.to_query() |> Query.from() |> TrashQuery.where_kept() end end
27.709386
83
0.589734
f762ba8343f833019af1fe7934fd4247538a1ff4
1,123
exs
Elixir
first-last-character/config/config.exs
crsanti/codewars-elixir
7e7d9bceea5db8b965ecc1e17be52bc2aeafa4f0
[ "MIT" ]
2
2021-08-18T11:31:31.000Z
2021-08-24T00:25:08.000Z
first-last-character/config/config.exs
crsanti/codewars-elixir
7e7d9bceea5db8b965ecc1e17be52bc2aeafa4f0
[ "MIT" ]
null
null
null
first-last-character/config/config.exs
crsanti/codewars-elixir
7e7d9bceea5db8b965ecc1e17be52bc2aeafa4f0
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :trimmer, key: :value # # and access this configuration in your application as: # # Application.get_env(:trimmer, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.225806
73
0.751558
f762e4c4e14c16b44cd197a5a9053372cbf05ea4
711
ex
Elixir
lib/chatroom_web/gettext.ex
hotpyn/phoenix-chat-demo
0726e6d4dc9482230a1e4d2b3edbe83b19924521
[ "MIT" ]
null
null
null
lib/chatroom_web/gettext.ex
hotpyn/phoenix-chat-demo
0726e6d4dc9482230a1e4d2b3edbe83b19924521
[ "MIT" ]
2
2021-03-09T12:17:18.000Z
2021-05-10T02:09:33.000Z
lib/chatroom_web/gettext.ex
hotpyn/phoenix-chat-demo
0726e6d4dc9482230a1e4d2b3edbe83b19924521
[ "MIT" ]
null
null
null
defmodule ChatroomWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import ChatroomWeb.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :chatroom end
28.44
72
0.682138
f7630ccefbdf7f1dd88266ea75b2ea48d58a93c9
932
exs
Elixir
issues/mix.exs
valevalorin/learning-elixir
cb7121b808341160ff225ea1ba61af1438c1b9b1
[ "MIT" ]
null
null
null
issues/mix.exs
valevalorin/learning-elixir
cb7121b808341160ff225ea1ba61af1438c1b9b1
[ "MIT" ]
null
null
null
issues/mix.exs
valevalorin/learning-elixir
cb7121b808341160ff225ea1ba61af1438c1b9b1
[ "MIT" ]
null
null
null
defmodule Issues.Mixfile do use Mix.Project def project do [app: :issues, version: "0.0.1", elixir: "~> 1.0", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, escript: escript_config, deps: deps] end # Configuration for the OTP application # # Type `mix help compile.app` for more information def application do [ applications: [ :logger, :httpoison, :jsx ] ] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type `mix help deps` for more examples and options defp deps do [ { :httpoison, "~> 0.4" }, { :jsx, "~> 2.0" }, { :ex_doc, github: "elixir-lang/ex_doc" }, {:earmark, ">= 0.0.0"} ] end defp escript_config do [ main_module: Issues.CLI ] end end
20.711111
77
0.572961
f76348e0f768ad7789c83cedc5b3a5e3cab44d7c
358
exs
Elixir
test/pummpcomm/history/clear_alarm_test.exs
infinity-aps/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
15
2017-08-31T00:58:47.000Z
2020-01-12T03:53:13.000Z
test/pummpcomm/history/clear_alarm_test.exs
vladhj38/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
1
2017-09-15T02:09:31.000Z
2017-09-15T02:09:31.000Z
test/pummpcomm/history/clear_alarm_test.exs
vladhj38/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
3
2017-09-10T17:24:59.000Z
2019-09-10T19:41:49.000Z
defmodule Pummpcomm.History.ClearAlarmTest do use ExUnit.Case test "Clear Alarm" do {:ok, history_page} = Base.decode16("0C3D760F0C050F") decoded_events = Pummpcomm.History.decode_records(history_page, %{}) assert {:clear_alarm, %{timestamp: ~N[2015-04-05 12:15:54], raw: ^history_page}} = Enum.at(decoded_events, 0) end end
29.833333
86
0.695531
f7634f410ebed7489f59fff1727daf02ca3be09a
3,467
exs
Elixir
test/file_utils_test.exs
akoutmos/ex_todo
f1aaf2ccb4ecdefb3fb48a36ef2cc76a0d9045fa
[ "MIT" ]
14
2019-06-18T04:56:18.000Z
2021-03-22T07:59:43.000Z
test/file_utils_test.exs
akoutmos/ex_todo
f1aaf2ccb4ecdefb3fb48a36ef2cc76a0d9045fa
[ "MIT" ]
null
null
null
test/file_utils_test.exs
akoutmos/ex_todo
f1aaf2ccb4ecdefb3fb48a36ef2cc76a0d9045fa
[ "MIT" ]
null
null
null
defmodule FilUtilsTest do use ExUnit.Case alias ExTodo.{Config, FileUtils} describe "get_all_files/2" do test "should return a list of all the files that match the catch all glob" do files = get_all_sample_files() assert files == [ "test/sample_files/c_sample.c", "test/sample_files/ex_sample.ex", "test/sample_files/js/js_sample.js" ] end test "should return a list of all the files that match a certain file glob" do files = %Config{} |> FileUtils.get_all_files("./**/*.c") |> Enum.sort() assert files == ["test/sample_files/c_sample.c"] end test "should return a list of all files except the skipped files" do files = get_all_sample_files(%Config{skip_patterns: [~r/c_sample\.c/]}) assert files == [ "test/sample_files/ex_sample.ex", "test/sample_files/js/js_sample.js" ] end test "should return a list of all files except the skipped directories" do files = get_all_sample_files(%Config{skip_patterns: [~r/test\/sample_files\/js/]}) assert files == [ "test/sample_files/c_sample.c", "test/sample_files/ex_sample.ex" ] end end describe "read_file_list_contents/1" do test "should read the contents of all the files provided" do file_paths = get_all_sample_files() files_contents = file_paths |> FileUtils.read_file_list_contents() Enum.each(files_contents, fn {file_path, contents} -> assert file_path in file_paths assert String.length(contents) > 0 end) end test "should return an empty list if file list is empty" do files = %Config{} |> FileUtils.get_all_files("./**/*.no_file") |> FileUtils.read_file_list_contents() assert files == [] end end describe "get_file_list_codetags/2" do test "should return all the configured codetags found within some files" do config = %Config{skip_patterns: [~r/c_sample\.c/, ~r/js_sample\.js/]} files = get_all_sample_files(config) [{"test/sample_files/ex_sample.ex", codetag_results}] = files |> FileUtils.read_file_list_contents() |> FileUtils.get_file_list_codetags(config) assert length(codetag_results) == 2 end test "should return an empty list if no codetags are found within some files" do config = %Config{ skip_patterns: [~r/c_sample\.c/, ~r/js_sample\.js/], supported_codetags: [] } files = get_all_sample_files(config) results = files |> FileUtils.read_file_list_contents() |> FileUtils.get_file_list_codetags(config) assert results == [] end test "should return a list of files that only fullfil the configured codetags" do config = %Config{ skip_patterns: [~r/c_sample\.c/, ~r/js_sample\.js/], supported_codetags: ["FIXME"] } files = get_all_sample_files(config) [{"test/sample_files/ex_sample.ex", codetag_results}] = files |> FileUtils.read_file_list_contents() |> FileUtils.get_file_list_codetags(config) assert length(codetag_results) == 1 end end defp get_all_sample_files(config \\ %Config{}) do config |> FileUtils.get_all_files("./test/sample_files/**") |> Enum.sort() end end
28.652893
88
0.626478
f763627173d2f844022e64d6cf37a1ee693d6832
4,486
ex
Elixir
clients/cloud_support/lib/google_api/cloud_support/v2beta/api/case_classifications.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_support/lib/google_api/cloud_support/v2beta/api/case_classifications.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_support/lib/google_api/cloud_support/v2beta/api/case_classifications.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudSupport.V2beta.Api.CaseClassifications do @moduledoc """ API calls for all endpoints tagged `CaseClassifications`. """ alias GoogleApi.CloudSupport.V2beta.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Retrieve valid classifications to be used when creating a support case. The classications are hierarchical, with each classification containing all levels of the hierarchy, separated by " > ". For example "Technical Issue > Compute > Compute Engine". ## Parameters * `connection` (*type:* `GoogleApi.CloudSupport.V2beta.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of cases fetched with each request. * `:pageToken` (*type:* `String.t`) - A token identifying the page of results to return. If unspecified, the first page is retrieved. * `:query` (*type:* `String.t`) - An expression written in the Cloud filter language. If non-empty, then only cases whose fields match the filter are returned. If empty, then no messages are filtered out. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudSupport.V2beta.Model.SearchCaseClassificationsResponse{}}` on success * `{:error, info}` on failure """ @spec cloudsupport_case_classifications_search(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.CloudSupport.V2beta.Model.SearchCaseClassificationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudsupport_case_classifications_search(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query, :query => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2beta/caseClassifications:search", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.CloudSupport.V2beta.Model.SearchCaseClassificationsResponse{}] ) end end
48.236559
252
0.667856
f7636efcf63ea0028ab11ba3b0a4a7180978f8bb
1,811
exs
Elixir
apps/banking_account_manager/mix.exs
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
apps/banking_account_manager/mix.exs
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
apps/banking_account_manager/mix.exs
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
defmodule BankingAccountManager.MixProject do use Mix.Project def project do [ app: :banking_account_manager, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps(), test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ] ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {BankingAccountManager.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:ecto_sql, "~> 3.1"}, {:postgrex, ">= 0.0.0"}, {:jason, "~> 1.0"}, {:brcpfcnpj, "~> 0.2.0"}, {:faker, "~> 0.13", only: :test} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
26.632353
79
0.586969
f76374eddaf0e99dcbe4a76f619a7359e6dbf3e2
512
ex
Elixir
lib/yacto.ex
gumi/yacto
b346e879775e974057ff25d5aae63688df7d4d07
[ "Apache-2.0" ]
56
2017-11-30T02:07:07.000Z
2022-02-16T17:38:42.000Z
lib/yacto.ex
gumi/yacto
b346e879775e974057ff25d5aae63688df7d4d07
[ "Apache-2.0" ]
22
2018-01-04T00:34:51.000Z
2021-08-01T06:52:10.000Z
lib/yacto.ex
gumi/yacto
b346e879775e974057ff25d5aae63688df7d4d07
[ "Apache-2.0" ]
13
2018-08-08T05:32:42.000Z
2021-07-30T14:57:35.000Z
defmodule Yacto do @external_resource "README.md" @moduledoc File.read!("README.md") |> String.split(~r/<!-- MDOC !-->/) |> Enum.fetch!(1) def transaction(databases, fun, opts \\ []) do dbopts = Keyword.get(opts, :databases) f = fn {dbname, dbkey} -> Yacto.DB.repo(dbname, shard_key: dbkey, databases: dbopts) dbname -> Yacto.DB.repo(dbname, databases: dbopts) end repos = Enum.map(databases, f) Yacto.XA.transaction(repos, fun, opts) end end
26.947368
83
0.609375
f7637a6251054a4ebda9440d18b6e424cdaf91de
2,332
ex
Elixir
packages/templates/src/project/potionx/lib/{{ appName }}_web/telemetry.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
31
2021-02-16T20:50:46.000Z
2022-02-03T10:38:07.000Z
packages/templates/src/project/potionx/lib/{{ appName }}_web/telemetry.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
6
2021-04-07T21:50:20.000Z
2022-02-06T21:54:04.000Z
packages/templates/src/project/potionx/lib/{{ appName }}_web/telemetry.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
4
2021-03-25T17:59:44.000Z
2021-04-25T16:28:22.000Z
defmodule <%= webNamespace %>.Telemetry do use Supervisor import Telemetry.Metrics def start_link(arg) do Supervisor.start_link(__MODULE__, arg, name: __MODULE__) end @impl true def init(_arg) do children = [ # Telemetry poller will execute the given period measurements # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} # Add reporters as children of your supervision tree. # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} ] Supervisor.init(children, strategy: :one_for_one) end def metrics do [ # Phoenix Metrics summary("phoenix.endpoint.stop.duration", unit: {:native, :millisecond} ), summary("phoenix.router_dispatch.stop.duration", tags: [:route], unit: {:native, :millisecond} ), # Database Metrics summary("<%= appName %>.repo.query.total_time", unit: {:native, :millisecond}, description: "The sum of the other measurements" ), summary("<%= appName %>.repo.query.decode_time", unit: {:native, :millisecond}, description: "The time spent decoding the data received from the database" ), summary("<%= appName %>.repo.query.query_time", unit: {:native, :millisecond}, description: "The time spent executing the query" ), summary("<%= appName %>.repo.query.queue_time", unit: {:native, :millisecond}, description: "The time spent waiting for a database connection" ), summary("<%= appName %>.repo.query.idle_time", unit: {:native, :millisecond}, description: "The time the connection spent waiting before being checked out for the query" ), # VM Metrics summary("vm.memory.total", unit: {:byte, :kilobyte}), summary("vm.total_run_queue_lengths.total"), summary("vm.total_run_queue_lengths.cpu"), summary("vm.total_run_queue_lengths.io") ] end defp periodic_measurements do [ # A module, function and arguments to be invoked periodically. # This function must call :telemetry.execute/3 and a metric must be added above. # {<%= webNamespace %>, :count_users, []} ] end end
32.388889
88
0.640223
f76405551cf8057d07f4692b6d10c1e1719fd621
753
exs
Elixir
test/features/developer_sees_navigation_bar_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
460
2016-12-28T21:50:05.000Z
2022-03-16T14:34:08.000Z
test/features/developer_sees_navigation_bar_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
412
2016-12-27T17:32:01.000Z
2021-09-17T23:51:47.000Z
test/features/developer_sees_navigation_bar_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
140
2017-01-06T06:55:58.000Z
2022-02-04T13:35:21.000Z
defmodule DeveloperSeesNavigationBarTest do use Tilex.IntegrationCase, async: true alias Tilex.Integration.Pages.Navigation describe "when developer is not authenticated" do test "there is no link on admin navbar", %{session: session} do link_texts = session |> visit("/") |> get_texts(Navigation.item_query()) assert link_texts == [] end end describe "when developer is authenticated" do setup [:authenticated_developer] test "there are links on admin navbar", %{session: session} do link_texts = session |> visit("/") |> get_texts(Navigation.item_query()) assert link_texts == ["Rock Teer", "Sign Out", "Create Post", "Profile"] end end end
25.1
78
0.649402
f76408fde10223e4fa258cc13493d386652d4f57
4,346
ex
Elixir
lib/oli_web/live/sections/edit_view.ex
Simon-Initiative/oli-torus
7f3eaeaa18ca8837e5afbff3e8899ae13b49de8b
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
lib/oli_web/live/sections/edit_view.ex
Simon-Initiative/oli-torus
7f3eaeaa18ca8837e5afbff3e8899ae13b49de8b
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
lib/oli_web/live/sections/edit_view.ex
Simon-Initiative/oli-torus
7f3eaeaa18ca8837e5afbff3e8899ae13b49de8b
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule OliWeb.Sections.EditView do use Surface.LiveView alias OliWeb.Common.{Breadcrumb} alias OliWeb.Common.Properties.{Groups, Group} alias OliWeb.Router.Helpers, as: Routes alias Oli.Delivery.Sections alias OliWeb.Sections.{MainDetails, OpenFreeSettings, LtiSettings, PaywallSettings} alias Surface.Components.{Form} alias Oli.Branding alias OliWeb.Sections.Mount data breadcrumbs, :any data title, :string, default: "Edit Section Details" data section, :any, default: nil data changeset, :any data is_admin, :boolean data brands, :list defp set_breadcrumbs(type, section) do OliWeb.Sections.OverviewView.set_breadcrumbs(type, section) |> breadcrumb(section) end def breadcrumb(previous, section) do previous ++ [ Breadcrumb.new(%{ full_title: "Edit Section", link: Routes.live_path(OliWeb.Endpoint, __MODULE__, section.slug) }) ] end def mount(%{"section_slug" => section_slug}, session, socket) do case Mount.for(section_slug, session) do {:error, e} -> Mount.handle_error(socket, {:error, e}) {type, _, section} -> available_brands = Branding.list_brands() |> Enum.map(fn brand -> {brand.name, brand.id} end) {:ok, assign(socket, brands: available_brands, changeset: Sections.change_section(section), is_admin: type == :admin, breadcrumbs: set_breadcrumbs(type, section), section: section )} end end def render(assigns) do ~F""" <Form as={:section} for={@changeset} change="validate" submit="save" opts={autocomplete: "off"}> <Groups> <Group label="Settings" description="Manage the course section settings"> <MainDetails changeset={@changeset} disabled={false} is_admin={@is_admin} brands={@brands} /> </Group> {#if @section.open_and_free} <OpenFreeSettings is_admin={@is_admin} changeset={@changeset} disabled={false}/> {#else} <LtiSettings section={@section}/> {/if} <PaywallSettings is_admin={@is_admin} changeset={@changeset} disabled={!can_change_payment?(@section)}/> </Groups> </Form> """ end def handle_event("validate", %{"section" => params}, socket) do params = convert_dates(params) changeset = socket.assigns.section |> Sections.change_section(params) {:noreply, assign(socket, changeset: changeset)} end def handle_event("save", %{"section" => params}, socket) do params = convert_dates(params) case Sections.update_section(socket.assigns.section, params) do {:ok, section} -> socket = put_flash(socket, :info, "Section changes saved") {:noreply, assign(socket, section: section, changeset: Sections.change_section(section))} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end def parse_and_convert_start_end_dates_to_utc(start_date, end_date, from_timezone) do section_timezone = Timex.Timezone.get(from_timezone) utc_timezone = Timex.Timezone.get(:utc, Timex.now()) utc_start_date = case start_date do start_date when start_date == nil or start_date == "" or not is_binary(start_date) -> start_date start_date -> start_date |> Timex.parse!("%Y-%m-%d", :strftime) |> Timex.to_datetime(section_timezone) |> Timex.Timezone.convert(utc_timezone) end utc_end_date = case end_date do end_date when end_date == nil or end_date == "" or not is_binary(end_date) -> end_date end_date -> end_date |> Timex.parse!("%Y-%m-%d", :strftime) |> Timex.to_datetime(section_timezone) |> Timex.Timezone.convert(utc_timezone) end {utc_start_date, utc_end_date} end defp convert_dates(params) do {utc_start_date, utc_end_date} = parse_and_convert_start_end_dates_to_utc( params["start_date"], params["end_date"], params["timezone"] ) params |> Map.put("start_date", utc_start_date) |> Map.put("end_date", utc_end_date) end defp can_change_payment?(section) do is_nil(section.blueprint_id) end end
29.972414
112
0.64174
f7643229b31c098a2bdf5bc38d6f029e39c97842
4,302
exs
Elixir
test/console_web/controllers/invitation_controller_test.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
null
null
null
test/console_web/controllers/invitation_controller_test.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
1
2021-04-03T09:29:31.000Z
2021-04-03T09:29:31.000Z
test/console_web/controllers/invitation_controller_test.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
null
null
null
defmodule ConsoleWeb.InvitationControllerTest do use ConsoleWeb.ConnCase import Plug.Conn import Phoenix.ConnTest import Console.Factory alias Console.Organizations describe "invitations" do setup [:authenticate_user] test "creates invitations properly", %{conn: conn} do current_organization_id = conn |> get_req_header("organization") |> List.first() another_org = insert(:organization) assert_error_sent 404, fn -> post conn, invitation_path(conn, :create), %{ "invitation" => %{}} end assert_error_sent 404, fn -> post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => another_org.id }} end resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id }} assert json_response(resp_conn, 422) == %{ "errors" => %{ "email" => ["Email is required"], "role" => ["Role is required"] } } resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id, "email" => "test@test", "role" => "read" } } assert json_response(resp_conn, 201) current_user = resp_conn.assigns.current_user resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id, "email" => current_user.email, "role" => "read" } } assert json_response(resp_conn, 403) # cannot invite yourself to org again end test "can accept invitations properly", %{conn: conn} do current_organization_id = conn |> get_req_header("organization") |> List.first() resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id, "email" => "test@test", "role" => "read" } } invitation = json_response(resp_conn, 201) |> Map.get("id") |> Organizations.get_invitation!() user = params_for(:user) {:ok, organization} = Organizations.create_organization(user, params_for(:organization)) conn2 = conn |> put_req_header("accept", "application/json") |> put_req_header("authorization", user.id <> " " <> user.email) |> put_req_header("organization", organization.id) resp_conn = post conn2, user_join_from_invitation_path(conn2, :accept), %{ "invitation" => %{ "token" => invitation.token } } assert response(resp_conn, 200) end test "can delete invitations properly", %{conn: conn} do current_organization_id = conn |> get_req_header("organization") |> List.first() resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id, "email" => "test@test", "role" => "read" } } invitation = json_response(resp_conn, 201) |> Map.get("id") |> Organizations.get_invitation!() resp_conn = delete conn, invitation_path(conn, :delete, invitation.id) assert response(resp_conn, 204) resp_conn = post conn, invitation_path(conn, :create), %{ "invitation" => %{ "organization" => current_organization_id, "email" => "test@test", "role" => "read" } } invitation = json_response(resp_conn, 201) |> Map.get("id") |> Organizations.get_invitation!() user = params_for(:user) {:ok, organization} = Organizations.create_organization(user, params_for(:organization)) conn2 = conn |> put_req_header("accept", "application/json") |> put_req_header("authorization", user.id <> " " <> user.email) |> put_req_header("organization", organization.id) post conn2, user_join_from_invitation_path(conn2, :accept), %{ "invitation" => %{ "token" => invitation.token } } resp_conn = delete conn, invitation_path(conn, :delete, invitation.id) assert response(resp_conn, 403) end end end
32.590909
127
0.592283
f76440c4775677eb536944e693375d2880174f6b
42,695
ex
Elixir
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/api/partners.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/api/partners.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/api/partners.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.AndroidDeviceProvisioning.V1.Api.Partners do @moduledoc """ API calls for all endpoints tagged `Partners`. """ alias GoogleApi.AndroidDeviceProvisioning.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Creates a customer for zero-touch enrollment. After the method returns successfully, admin and owner roles can manage devices and EMM configs by calling API methods or using their zero-touch enrollment portal. The customer receives an email that welcomes them to zero-touch enrollment and explains how to sign into the portal. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource ID in the format `partners/[PARTNER_ID]` that identifies the reseller. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.CreateCustomerRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Company{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_customers_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Company.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_customers_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/customers", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Company{}]) end @doc """ Lists the customers that are enrolled to the reseller identified by the `partnerId` argument. This list includes customers that the reseller created and customers that enrolled themselves using the portal. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of results to be returned. If not specified or 0, all the records are returned. * `:pageToken` (*type:* `String.t`) - A token identifying a page of results returned by the server. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListCustomersResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_customers_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.ListCustomersResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_customers_list( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/partners/{+partnerId}/customers", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListCustomersResponse{}] ) end @doc """ Claims a device for a customer and adds it to zero-touch enrollment. If the device is already claimed by another customer, the call returns an error. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.ClaimDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.ClaimDeviceResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_claim( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.ClaimDeviceResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_claim( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:claim", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.ClaimDeviceResponse{}] ) end @doc """ Claims a batch of devices for a customer asynchronously. Adds the devices to zero-touch enrollment. To learn more, read [Long‑running batch operations](/zero-touch/guides/how-it-works#operations). ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.ClaimDevicesRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_claim_async( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_claim_async( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:claimAsync", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}] ) end @doc """ Finds devices by hardware identifiers, such as IMEI. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByDeviceIdentifierRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByDeviceIdentifierResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_find_by_identifier( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByDeviceIdentifierResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_find_by_identifier( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:findByIdentifier", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [ struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByDeviceIdentifierResponse{} ] ) end @doc """ Finds devices claimed for customers. The results only contain devices registered to the reseller that's identified by the `partnerId` argument. The customer's devices purchased from other resellers don't appear in the results. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_find_by_owner( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_find_by_owner( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:findByOwner", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerResponse{}] ) end @doc """ Gets a device. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The device API resource name in the format `partners/[PARTNER_ID]/devices/[DEVICE_ID]`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Device{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Device.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Device{}]) end @doc """ Updates reseller metadata associated with the device. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `metadata_owner_id` (*type:* `String.t`) - Required. The owner of the newly set metadata. Set this to the partner ID. * `device_id` (*type:* `String.t`) - Required. The ID of the device. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceMetadata{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_metadata( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceMetadata.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_metadata( connection, metadata_owner_id, device_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+metadataOwnerId}/devices/{+deviceId}/metadata", %{ "metadataOwnerId" => URI.encode(metadata_owner_id, &URI.char_unreserved?/1), "deviceId" => URI.encode(device_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceMetadata{}] ) end @doc """ Unclaims a device from a customer and removes it from zero-touch enrollment. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The ID of the reseller partner. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.UnclaimDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_unclaim( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Empty.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_unclaim( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:unclaim", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Empty{}]) end @doc """ Unclaims a batch of devices for a customer asynchronously. Removes the devices from zero-touch enrollment. To learn more, read [Long‑running batch operations](/zero-touch/guides/how-it-works#operations). ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The reseller partner ID. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.UnclaimDevicesRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_unclaim_async( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_unclaim_async( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:unclaimAsync", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}] ) end @doc """ Updates the reseller metadata attached to a batch of devices. This method updates devices asynchronously and returns an `Operation` that can be used to track progress. Read [Long‑running batch operations](/zero-touch/guides/how-it-works#operations). ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `partner_id` (*type:* `String.t`) - Required. The reseller partner ID. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataInBatchRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_devices_update_metadata_async( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_devices_update_metadata_async( connection, partner_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/partners/{+partnerId}/devices:updateMetadataAsync", %{ "partnerId" => URI.encode(partner_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.Operation{}] ) end @doc """ Lists the vendors of the partner. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name in the format `partners/[PARTNER_ID]`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of results to be returned. * `:pageToken` (*type:* `String.t`) - A token identifying a page of results returned by the server. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorsResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_vendors_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorsResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_vendors_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/vendors", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorsResponse{}] ) end @doc """ Lists the customers of the vendor. ## Parameters * `connection` (*type:* `GoogleApi.AndroidDeviceProvisioning.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name in the format `partners/[PARTNER_ID]/vendors/[VENDOR_ID]`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:$.xgafv` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of results to be returned. * `:pageToken` (*type:* `String.t`) - A token identifying a page of results returned by the server. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorCustomersResponse{}}` on success * `{:error, info}` on failure """ @spec androiddeviceprovisioning_partners_vendors_customers_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorCustomersResponse.t()} | {:error, Tesla.Env.t()} def androiddeviceprovisioning_partners_vendors_customers_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/customers", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidDeviceProvisioning.V1.Model.ListVendorCustomersResponse{}] ) end end
43.700102
196
0.62293
f76445ae2732dddda6d9f50a118ed2540a826117
535
ex
Elixir
nfc/lib/nfc/nif.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
7
2020-11-18T11:29:20.000Z
2022-01-16T03:16:14.000Z
nfc/lib/nfc/nif.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
null
null
null
nfc/lib/nfc/nif.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
1
2021-01-06T15:40:46.000Z
2021-01-06T15:40:46.000Z
defmodule NFC.Nif do @on_load {:load_nif, 0} @compile {:autoload, false} @moduledoc false def load_nif() do nif_binary = Application.app_dir(:nfc, "priv/nfc_nif") libnfc_install_dir = Application.app_dir(:nfc, "priv/lib") IO.inspect(File.ls!(libnfc_install_dir)) System.put_env("LD_LIBRARY_PATH", libnfc_install_dir) :erlang.load_nif(to_charlist(nif_binary), 0) end def open(_pid) do :erlang.nif_error(:nif_not_loaded) end def close(_nfc) do :erlang.nif_error(:nif_not_loaded) end end
23.26087
62
0.71028
f7645ba3df4cf72fd3a7787d56bfaa02e7723fe2
2,411
exs
Elixir
test/automated/esp_ex/message_store_test.exs
Carburetor/esp_ex
0a0ab02c71945e521b213befc0421a4642c9e07b
[ "MIT" ]
null
null
null
test/automated/esp_ex/message_store_test.exs
Carburetor/esp_ex
0a0ab02c71945e521b213befc0421a4642c9e07b
[ "MIT" ]
1
2018-05-11T04:27:54.000Z
2018-05-11T04:27:54.000Z
test/automated/esp_ex/message_store_test.exs
Carburetor/esp_ex
0a0ab02c71945e521b213befc0421a4642c9e07b
[ "MIT" ]
1
2018-10-30T06:08:02.000Z
2018-10-30T06:08:02.000Z
defmodule EspEx.MessageStoreTest do use ExUnit.Case, async: true alias EspEx.MessageStore.Static, as: MessageStore alias EspEx.RawEvent alias EspEx.StreamName @stream_name %StreamName{category: "campaign", identifier: "123", types: []} @empty_stream %StreamName{category: "empty", identifier: nil, types: []} @raw_event %RawEvent{ id: "11111111", stream_name: @stream_name, type: "Updated", data: %{name: "Unnamed"} } describe "MessageStore.write_initial!" do test "doesn't raises on first message" do MessageStore.write_initial!(@raw_event) end end describe "MessageStore.write!" do test "returns 3" do version = MessageStore.write!(@raw_event) assert version == 3 end end describe "MessageStore.read_last" do test "returns %RawEvent when stream has events" do raw_event = MessageStore.read_last(@stream_name) assert raw_event.position == 2 && raw_event.id == "uuid" end test "returns nil when stream is empty" do raw_event = MessageStore.read_last(@empty_stream) assert raw_event == nil end end describe "MessageStore.read_batch" do test "returns list of %RawEvent when stream has events" do raw_events = MessageStore.read_batch(@stream_name) assert length(raw_events) == 3 end test "returns [] when reading after last event" do raw_events = MessageStore.read_batch(@stream_name, 3) assert raw_events == [] end test "returns list of %RawEvent with max size of batch_size" do raw_events = MessageStore.read_batch(@stream_name, 0, 2) assert length(raw_events) == 2 end end describe "MessageStore.read_version" do test "returns last event position" do version = MessageStore.read_version(@stream_name) assert version == 2 end test "returns nil when stream is empty" do version = MessageStore.read_version(@empty_stream) assert version == nil end end describe "MessageStore.stream" do test "streams raw events as read from batch" do raw_events = MessageStore.stream(@stream_name) |> Enum.to_list() assert length(raw_events) == 3 end test "streams raw events as read from batch even in different chunks" do raw_events = MessageStore.stream(@stream_name, 1, 1) |> Enum.to_list() assert length(raw_events) == 2 end end end
25.924731
78
0.683119
f7645c71a73a45c84653e45e8160b4769955ed92
145
exs
Elixir
config/prod.exs
mijailr/alertas.ec
f33f0c0236675e4749b327f13612a0f67aaf9a77
[ "MIT" ]
8
2020-03-15T19:07:58.000Z
2022-03-10T19:06:55.000Z
config/prod.exs
mijailr/alertas.ec
f33f0c0236675e4749b327f13612a0f67aaf9a77
[ "MIT" ]
223
2020-04-14T10:43:50.000Z
2021-06-21T11:40:34.000Z
config/prod.exs
mijailr/alertas.ec
f33f0c0236675e4749b327f13612a0f67aaf9a77
[ "MIT" ]
null
null
null
import Config config :alertas_ec, AlertasEc.Repo, url: System.get_env("DATABASE_URL"), migration_primary_key: [name: :id, type: :binary_id]
24.166667
54
0.751724
f76464f5ede1a9edfcdfddc8b8e0f96a5c79f0a3
5,270
exs
Elixir
test/elixir/test/config_test.exs
RGS-IT-Development/couchdb
e25ae03a75eafe5ecb286399da5186f2fac25835
[ "Apache-2.0" ]
null
null
null
test/elixir/test/config_test.exs
RGS-IT-Development/couchdb
e25ae03a75eafe5ecb286399da5186f2fac25835
[ "Apache-2.0" ]
1
2018-02-08T23:08:43.000Z
2018-02-08T23:08:43.000Z
test/elixir/test/config_test.exs
RGS-IT-Development/couchdb
e25ae03a75eafe5ecb286399da5186f2fac25835
[ "Apache-2.0" ]
null
null
null
defmodule ConfigTest do use CouchTestCase @moduletag :config @moduletag kind: :single_node @moduledoc """ Test CouchDB config API This is a port of the config.js suite """ setup do config_url = "/_node/_local/_config" resp = Couch.get(config_url) assert resp.status_code == 200 {:ok, config: resp.body, config_url: config_url} end def set_config(context, section, key, val) do set_config(context, section, key, val, 200) end def set_config(context, section, key, val, status_assert) do url = "#{context[:config_url]}/#{section}/#{key}" headers = ["X-Couch-Persist": "false"] resp = Couch.put(url, headers: headers, body: :jiffy.encode(val)) if status_assert do assert resp.status_code == status_assert end resp.body end def get_config(context, section) do get_config(context, section, nil, 200) end def get_config(context, section, key) do get_config(context, section, key, 200) end def get_config(context, section, key, status_assert) do url = if key do "#{context[:config_url]}/#{section}/#{key}" else "#{context[:config_url]}/#{section}" end resp = Couch.get(url) if status_assert do assert resp.status_code == status_assert end resp.body end def delete_config(context, section, key) do delete_config(context, section, key, 200) end def delete_config(context, section, key, status_assert) do url = "#{context[:config_url]}/#{section}/#{key}" resp = Couch.delete(url) if status_assert do assert resp.status_code == status_assert end end test "Standard config options are present", context do assert context[:config]["chttpd"]["port"] end test "Settings can be altered with undefined whitelist allowing any change", context do refute context["config"]["chttpd"]["config_whitelist"], "Default whitelist is empty" set_config(context, "test", "foo", "bar") assert get_config(context, "test")["foo"] == "bar" assert get_config(context, "test", "foo") == "bar" end test "Server-side password hashing, and raw updates disabling that", context do plain_pass = "s3cret" set_config(context, "admins", "administrator", plain_pass) assert Couch.login("administrator", plain_pass) hash_pass = get_config(context, "admins", "administrator") assert Regex.match?(~r/^-pbkdf2-/, hash_pass) or Regex.match?(~r/^-hashed-/, hash_pass) delete_config(context, "admins", "administrator") assert Couch.delete("/_session").body["ok"] end test "Non-term whitelist values allow further modification of the whitelist", context do val = "!This is an invalid Erlang term!" set_config(context, "chttpd", "config_whitelist", val) assert val == get_config(context, "chttpd", "config_whitelist") delete_config(context, "chttpd", "config_whitelist") end test "Non-list whitelist values allow further modification of the whitelist", context do val = "{[yes, a_valid_erlang_term, but_unfortunately, not_a_list]}" set_config(context, "chttpd", "config_whitelist", val) assert val == get_config(context, "chttpd", "config_whitelist") delete_config(context, "chttpd", "config_whitelist") end test "Keys not in the whitelist may not be modified", context do val = "[{chttpd,config_whitelist}, {test,foo}]" set_config(context, "chttpd", "config_whitelist", val) assert val == get_config(context, "chttpd", "config_whitelist") set_config(context, "test", "foo", "PUT to whitelisted config variable") delete_config(context, "test", "foo") end test "Non-2-tuples in the whitelist are ignored", context do val = "[{chttpd,config_whitelist}, these, {are}, {nOt, 2, tuples}, [so], [they, will], [all, become, noops], {test,foo}]" set_config(context, "chttpd", "config_whitelist", val) assert val == get_config(context, "chttpd", "config_whitelist") set_config(context, "test", "foo", "PUT to whitelisted config variable") delete_config(context, "test", "foo") end test "Atoms, binaries, and strings suffice as whitelist sections and keys.", context do vals = ["{test,foo}", "{\"test\",\"foo\"}", "{<<\"test\">>,<<\"foo\">>}"] Enum.each(vals, fn pair -> set_config( context, "chttpd", "config_whitelist", "[{chttpd,config_whitelist}, #{pair}" ) pair_format = case String.at(pair, 1) do "t" -> "tuple" "\"" -> "string" "<" -> "binary" end set_config(context, "test", "foo", "PUT with #{pair_format}") delete_config(context, "test", "foo") end) delete_config(context, "chttpd", "config_whitelist") end test "Blacklist is functional", context do sections = [ "daemons", "external", "httpd_design_handlers", "httpd_db_handlers", "native_query_servers", "os_daemons", "query_servers" ] Enum.each(sections, fn section -> set_config(context, section, "wohali", "rules", 403) end) end test "Reload config", context do url = "#{context[:config_url]}/_reload" resp = Couch.post(url) assert resp.status_code == 200 end end
29.606742
121
0.651233
f7646abbe00324e6a9a847ff76df599f88fea3b7
4,597
ex
Elixir
lib/graphql/encoder.ex
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
9
2022-03-11T21:14:13.000Z
2022-03-31T14:13:38.000Z
lib/graphql/encoder.ex
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
null
null
null
lib/graphql/encoder.ex
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
null
null
null
defmodule GraphQL.Encoder do @moduledoc """ Functions to encode `GraphQL.Query` struct into a string """ alias GraphQL.{Node, Query, Variable} @doc """ Encodes a `GraphQL.Query` struct into a GraphQL query body """ @spec encode(Query.t()) :: String.t() def encode(%Query{} = query) do has_fragments? = valid?(query.fragments) has_variables? = valid?(query.variables) identation = 0 [ query.operation, " ", query.name, if(has_variables?, do: encode_variables(query.variables)), " {\n", encode_nodes(query.fields, identation + 2), "\n}", if(has_fragments?, do: "\n"), if(has_fragments?, do: encode_nodes(query.fragments, identation)) ] |> Enum.join() end # Variables defp encode_variables(variables) do [ "(", variables |> Enum.map(&encode_variable/1) |> Enum.join(", "), ")" ] |> Enum.join() end defp encode_variable(%Variable{} = var) do has_default? = var.default_value != nil [ "$", var.name, ": ", var.type, if(has_default?, do: " = "), encode_value(var.default_value) ] |> Enum.join() end defp encode_nodes(nil, _), do: "" defp encode_nodes([], _), do: "" defp encode_nodes(fields, identation) do fields |> Enum.map(&encode_node(&1, identation)) |> Enum.join("\n") end # Field defp encode_node(%Node{node_type: :field} = a_node, identation) do has_arguments? = valid?(a_node.arguments) has_nodes? = valid?(a_node.nodes) has_directives? = valid?(a_node.directives) [ String.duplicate(" ", identation), encode_field_alias(a_node.alias), encode_name(a_node.name), if(has_arguments?, do: encode_arguments(a_node.arguments)), if(has_directives?, do: " "), if(has_directives?, do: encode_directives(a_node.directives)), if(has_nodes?, do: " {\n"), encode_nodes(a_node.nodes, identation + 2), if(has_nodes?, do: "\n"), if(has_nodes?, do: String.duplicate(" ", identation)), if(has_nodes?, do: "}") ] |> Enum.join() end # Fragment reference defp encode_node(%Node{node_type: :fragment_ref} = a_node, identation) do [ String.duplicate(" ", identation), "...", a_node.name ] |> Enum.join() end # Fragment defp encode_node(%Node{node_type: :fragment} = fragment, identation) do [ String.duplicate(" ", identation), "fragment ", fragment.name, " on ", fragment.type, " {\n", fragment.nodes |> Enum.map(&encode_node(&1, identation + 2)) |> Enum.join("\n"), "\n", String.duplicate(" ", identation), "}" ] |> Enum.join() end # Inline Fragment defp encode_node(%Node{node_type: :inline_fragment} = a_node, identation) do [ String.duplicate(" ", identation), "... on ", a_node.type, " {\n", a_node.nodes |> Enum.map(&encode_node(&1, identation + 2)) |> Enum.join("\n"), "\n", String.duplicate(" ", identation), "}" ] |> Enum.join() end defp encode_name(name) when is_atom(name), do: Atom.to_string(name) defp encode_name(name) when is_binary(name), do: name defp encode_field_alias(nil), do: "" defp encode_field_alias(an_alias), do: "#{an_alias}: " # Arguments def encode_arguments(nil), do: "" def encode_arguments([]), do: "" def encode_arguments(map_or_keyword) do vars = map_or_keyword |> Enum.map(&encode_argument/1) |> Enum.join(", ") "(#{vars})" end def encode_argument({key, value}) do "#{key}: #{encode_value(value)}" end defp encode_value(v) do cond do is_binary(v) -> "\"#{v}\"" is_list(v) -> v |> Enum.map(&encode_value/1) |> Enum.join() is_map(v) -> parsed_v = v |> Enum.map(&encode_argument/1) |> Enum.join(", ") Enum.join(["{", parsed_v, "}"]) true -> case v do {:enum, v} -> v v -> "#{v}" end end end defp encode_directives(directives) do directives |> Enum.map(&encode_directive/1) |> Enum.join(" ") end defp encode_directive({key, arguments}) do [ "@", key, encode_arguments(arguments) ] |> Enum.join() end defp encode_directive(key) do ["@", key] |> Enum.join() end defp valid?(nil), do: false defp valid?([]), do: false defp valid?(a_map) when is_map(a_map), do: a_map != %{} defp valid?(_), do: true end
22.64532
86
0.567762
f7649a6260b0ef982eef4d57d9b6d214d15e5448
327
ex
Elixir
test/support/test_util.ex
slievr/kcl_ex
c1620ba68b56da1802e6e9fafdb3da14155b90d7
[ "Apache-2.0" ]
4
2017-12-19T15:27:54.000Z
2021-06-04T13:04:49.000Z
test/support/test_util.ex
slievr/kcl_ex
c1620ba68b56da1802e6e9fafdb3da14155b90d7
[ "Apache-2.0" ]
2
2021-03-05T12:01:24.000Z
2021-12-03T22:34:24.000Z
test/support/test_util.ex
slievr/kcl_ex
c1620ba68b56da1802e6e9fafdb3da14155b90d7
[ "Apache-2.0" ]
3
2021-02-17T16:14:11.000Z
2021-12-10T05:26:25.000Z
defmodule KinesisClient.TestUtil do def random_string do min = String.to_integer("10000000", 36) max = String.to_integer("ZZZZZZZZ", 36) max |> Kernel.-(min) |> :rand.uniform() |> Kernel.+(min) |> Integer.to_string(36) end def worker_ref() do "worker-#{:rand.uniform(10_000)}" end end
19.235294
43
0.626911
f764b11c068f9a563481816199a2c5415e54ce44
276
ex
Elixir
lib/jingle.ex
x4121/jingle
2e034b1f936b59d3ae2b29355c8a6d7c3fb435d1
[ "MIT" ]
null
null
null
lib/jingle.ex
x4121/jingle
2e034b1f936b59d3ae2b29355c8a6d7c3fb435d1
[ "MIT" ]
null
null
null
lib/jingle.ex
x4121/jingle
2e034b1f936b59d3ae2b29355c8a6d7c3fb435d1
[ "MIT" ]
null
null
null
defmodule Jingle do use Application def start(_type, _args) do import Supervisor.Spec, warn: false children = [ worker(Jingle.Repo, []) ] opts = [strategy: :one_for_one, name: Jingle.Supervisor] Supervisor.start_link(children, opts) end end
18.4
60
0.67029
f764c1e76c2fcceab1db42e3a90827d053ce6759
696
exs
Elixir
test/elixir_latex/latex_helpers_test.exs
moroz/elixir_latex
a7cd0ee5b1e82951dde8926cdaabd39551997f0c
[ "BSD-3-Clause" ]
1
2021-12-21T10:38:35.000Z
2021-12-21T10:38:35.000Z
test/elixir_latex/latex_helpers_test.exs
moroz/elixir_latex
a7cd0ee5b1e82951dde8926cdaabd39551997f0c
[ "BSD-3-Clause" ]
null
null
null
test/elixir_latex/latex_helpers_test.exs
moroz/elixir_latex
a7cd0ee5b1e82951dde8926cdaabd39551997f0c
[ "BSD-3-Clause" ]
null
null
null
defmodule ElixirLatex.LatexHelpersTest do use ExUnit.Case alias ElixirLatex.LatexHelpers @sample_text "\\documentclass[a4paper]{article}" test "escape_latex/1 replaces special LaTeX chars with escape sequences" do actual = LatexHelpers.escape_latex(@sample_text) assert actual == "\\textbackslash{}documentclass[a4paper]\\{article\\}" end describe "format_plain_as_latex/1" do @source_paragraph """ 你好,世界! 此為測試段落 """ @expected_paragraph "你好,世界!\\\\此為測試段落" test "converts single newlines to LaTeX newline literals" do actual = LatexHelpers.format_plain_as_latex(@source_paragraph) assert actual == @expected_paragraph end end end
26.769231
77
0.727011
f764c41e2bb6f481bbf565ec0337b24d37fa36ec
204
ex
Elixir
lib/sec_edgar.ex
david-christensen/sec_edgar
fd129d127a1b9e454cc5d215fd95b3eb37dcc70c
[ "MIT" ]
null
null
null
lib/sec_edgar.ex
david-christensen/sec_edgar
fd129d127a1b9e454cc5d215fd95b3eb37dcc70c
[ "MIT" ]
null
null
null
lib/sec_edgar.ex
david-christensen/sec_edgar
fd129d127a1b9e454cc5d215fd95b3eb37dcc70c
[ "MIT" ]
null
null
null
defmodule SecEdgar do @moduledoc """ Documentation for `SecEdgar`. """ @doc """ Hello world. ## Examples iex> SecEdgar.hello() :world """ def hello do :world end end
10.736842
31
0.563725
f764d328877b8663548ca646a01da3898b487808
267
exs
Elixir
priv/repo/migrations/20190426094325_create_users.exs
ritavaz02/Produtos
b29ed74e428eb9391ccd12460d1dcb005d040400
[ "MIT" ]
2
2019-10-10T11:57:29.000Z
2019-12-17T18:04:10.000Z
priv/repo/migrations/20190426094325_create_users.exs
ritavaz02/Produtos
b29ed74e428eb9391ccd12460d1dcb005d040400
[ "MIT" ]
86
2019-04-27T16:18:58.000Z
2021-05-28T23:13:36.000Z
priv/repo/migrations/20190426094325_create_users.exs
ritavaz02/Produtos
b29ed74e428eb9391ccd12460d1dcb005d040400
[ "MIT" ]
1
2020-07-16T04:52:47.000Z
2020-07-16T04:52:47.000Z
defmodule Chirper.Repo.Migrations.CreateUsers do use Ecto.Migration def change do create table(:users) do add :username, :string add :encrypted_password, :string timestamps() end create unique_index(:users, [:username]) end end
17.8
48
0.681648
f7652c0473a5d5193f05a6cf67b3564fae316cad
73
exs
Elixir
countdown/test/test_helper.exs
cashmann/phoenix-tutorial
ea37b9d54a79df9bc1351a948eb8f8400c5e62ff
[ "MIT" ]
null
null
null
countdown/test/test_helper.exs
cashmann/phoenix-tutorial
ea37b9d54a79df9bc1351a948eb8f8400c5e62ff
[ "MIT" ]
3
2021-03-09T20:36:45.000Z
2021-05-10T17:47:02.000Z
countdown/test/test_helper.exs
cashmann/phoenix-tutorial
ea37b9d54a79df9bc1351a948eb8f8400c5e62ff
[ "MIT" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Countdown.Repo, :manual)
14.6
55
0.767123
f765696879584684f42bcd289307834b78449748
1,081
exs
Elixir
test/ex_guard/notifier/tmux_test.exs
NOLAnuffsaid/ex_guard
513855563d10e3b93abdd29bf46f38ba310e21ea
[ "MIT" ]
80
2016-03-19T18:50:55.000Z
2021-07-15T11:05:47.000Z
test/ex_guard/notifier/tmux_test.exs
NOLAnuffsaid/ex_guard
513855563d10e3b93abdd29bf46f38ba310e21ea
[ "MIT" ]
33
2016-03-15T19:26:04.000Z
2022-01-24T16:01:44.000Z
test/ex_guard/notifier/tmux_test.exs
NOLAnuffsaid/ex_guard
513855563d10e3b93abdd29bf46f38ba310e21ea
[ "MIT" ]
14
2016-08-24T13:57:48.000Z
2020-12-15T11:58:52.000Z
defmodule ExGuard.Notifier.TMuxTest do use ExUnit.Case alias ExGuard.Notifier.TMux test "prepare TerminalNotifier command" do command = TMux.prepare_cmd(title: "unit test", message: "boo", status: :ok) assert command == ~s(tmux set -q status-left-bg green) command = TMux.prepare_cmd(title: "unit test", message: "boo", status: :error) assert command == ~s(tmux set -q status-left-bg red) command = TMux.prepare_cmd(title: "unit test", message: "boo", status: :pending) assert command == ~s(tmux set -q status-left-bg yellow) end test "tmux shouln't be available out of tmux session" do tmux_val = System.get_env("TMUX") if tmux_val, do: System.delete_env("TMUX") assert TMux.available?() == false if tmux_val, do: System.put_env("TMUX", tmux_val) end test "tmux should be available tmux session" do tmux_val = System.get_env("TMUX") if tmux_val, do: System.delete_env("TMUX") System.put_env("TMUX", "VAL") assert TMux.available?() == true if tmux_val, do: System.put_env("TMUX", tmux_val) end end
33.78125
84
0.683626
f7658a893b15a491d85b567049134aecf903711a
779
ex
Elixir
lib/channel_store.ex
MMore/slack-saved-items-export
d7d470c11a2927949f84fa5637968455f9319923
[ "MIT" ]
5
2021-07-16T05:27:52.000Z
2022-01-18T08:05:32.000Z
lib/channel_store.ex
MMore/slack-saved-items-export
d7d470c11a2927949f84fa5637968455f9319923
[ "MIT" ]
null
null
null
lib/channel_store.ex
MMore/slack-saved-items-export
d7d470c11a2927949f84fa5637968455f9319923
[ "MIT" ]
null
null
null
defmodule SSIExport.ChannelStore do alias SSIExport.DataAdapter use GenServer # Client def start_link(_args) do GenServer.start_link(__MODULE__, [], name: __MODULE__) end def get_channel_name(channel_id) do GenServer.call(__MODULE__, {:get_channel_name, channel_id}, :infinity) end # Server def init(init_arg) do {:ok, init_arg} end def handle_call({:get_channel_name, channel_id}, _from, state, data_mod \\ DataAdapter) do case List.keyfind(state, channel_id, 0) do nil -> channel_info = data_mod.get_channel_info(channel_id) new_state = [{channel_id, channel_info} | state] {:reply, channel_info, new_state} {_channel_id, channel_name} -> {:reply, channel_name, state} end end end
22.911765
92
0.689345